print function is calling before partial view - javascript

What I am trying to do is to open partial view in new window and call print function, but problem is that partial view renders after print function so I always get a blank page. I tried with $timeout function but I get the same result. For now, I have this but this is a hacky solution and I don't like it:
$scope.print = function() {
setTimeout(function() {
print()
}, 1000);
}
This is html of page that i try to open:
<div id="printWrapper" style="background-color:white;" ng-controller="accountContentController" ng-init="print()">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<!-- HEADER -->
<tr>
<td>
<img id="imgLogo" src="#Model.TicketPayOut.Logo" />
</td>
</tr>
<!--HEADER-->
<tr>
<td>
<label id="lblTerminalId" class="left-position padding-top-3 padding-left-3 text-style">#Translator.Translate("TERMINAL")</label>
<span class="left-position padding-top-3 text-style">:</span>
<label id="lblTerminalIdValue" class="left-position padding-top-3 padding-left-3 text-style"></label>
<div style="clear:both"></div>
<label id="lblTerminalName" class="left-position padding-left-3 text-style">#Translator.Translate("BET_OFFICE")</label>
<span class="left-post text-style">:</span>
<label id="lblTerminalNameValue" class="left-position padding-left-3 text-style"></label>
<label id="lblTerminalCityAddress" class="left-position padding-left-3 text-style" style="clear:both;"></label>
<label id="lblCompanyInfo" class="center-position text-style" style="clear:both;"></label>
<label id="lblCompanyAddress" class="center-position text-style" style="clear:both;"></label>
<label id="lblCompanyId" class="center-position text-style" style="clear:both;"></label>
</td>
</tr>
<tr>
<td class="border-top border-bottom">
<div style="padding:10px 0;">
<label id="lblStornoMessage" class="center-position text-style">#Translator.Translate("PAYOUT_CONFIRMATION")</label>
</div>
</td>
</tr>
<tr>
<td class="border-bottom">
<div style="height:25px;padding:10px 3px 0 3px;">
<label id="lblPayoutTicket" class="left-position text-style">#Translator.Translate("PAYOUT_TICKET")</label>
<label id="lblPinValue" class="right-position text-style">{{payoutTime | date: dateFormat }}</label>
</div>
</td>
</tr>
<tr>
<td>
<div style="padding:5px 3px;">
<label id="lblPinTicket" class="left-position text-style">#Translator.Translate("PIN")</label>
<label id="lblPinReturnValue" class="right-position text-style">{{ticketPin}}</label>
</div>
</td>
</tr>
<tr>
<td>
<div style="padding:5px 3px;">
<label id="lblPayinReturn" class="left-position text-style">#Translator.Translate("PAYOUT_AMOUNT")</label>
<label id="lblPayinReturnValue" class="right-position text-style">{{payoutAmount}}</label>
</div>
</td>
</tr>
<tr>
<td class="border-bottom">
<div style="padding:25px 3px 5px 3px;">
<label id="lblCreatedBy" class="left-post text-style">#Translator.Translate("CREATED_BY")</label>
<label id="lblCreatedByValue" class="right-position text-style">#User.Identity.Name</label>
</div>
</td>
</tr>
</table>
</div>
This is button on page where i have print option :
<div class="mr-10">
<div class="pull-right padding-8 mt5 col-lg-2 col-md-2">
<input type="submit" value="#Translator.Translate("CANCEL")" class="btn btn-block secondary-button save-changes padding-8" ng-click="CancelPayOutTicket(ticketPin)" />
</div>
<div class="pull-right padding-8 mt5 col-lg-2 col-md-2">
<input type="submit" value="#Translator.Translate("PAYOUT")" class="btn btn-block save-changes padding-8" ng-class="{'secondary-button':TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==true,'disabled_button':TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==false}" ng-disabled="TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==false" ng-click="FinishTicketPayout(ticketPin);ConfirmTicketPayOut(ticketPin,'#username')"/>
</div>
</div>
Is there any way to avoid setTimeout function and just call print function in new window and populate partial view with data?
EDIT: angular controller:
$scope.CheckTicket = function (ticketPin) {
if (ticketPin != null && ticketPin != "" && ticketPin != undefined) {
var promise = accountDataProviderService.checkTicketPayout(ticketPin);
$scope.checkPromise = promise;
promise.then(
function (response) {
$scope.showTicketPayout = true;
$scope.TicketsPayout = response;
},
function (err) {
$scope.showTicketPayout = false;
$scope.ticketNotFound = true;
$timeout(function ()
{
$scope.ticketNotFound = false;
}, ticketNotFound * 1000);
});
}
}
$scope.CloseMessage = function ()
{
$scope.ticketNotFound = false;
}
$scope.FinishTicketPayout = function (ticketPin)
{
accountDataProviderService.finishTicketPayOut(ticketPin)
.then(function (response) {
$scope.finishTicketPayOut = response;
localStorage.setItem("payoutTime", $scope.finishTicketPayOut.PayoutTime);
localStorage.setItem("payoutAmount", $scope.finishTicketPayOut.PayoutAmount);
});
}
$scope.ConfirmTicketPayOut = function (ticketPin, username) {
$scope.ticketPin = ticketPin;
localStorage.setItem("pin", ticketPin);
accountDataProviderService.confirmTicketPayOut(ticketPin, username)
.then(function (response) {
$scope.confirmTicketPayOut = response;
if ($scope.confirmTicketPayOut.Result == true) {
var newWindow = window.open("/print")
}
});
localStorage.clear();
}

make the data "package" a promise inside your controller:
angular.module("printModule").controller('printController', ['$scope', '$window', '$q', function ($scope, $window, $q) {
$scope.ticketPin = localStorage.getItem("pin");
$scope.payoutTime = localStorage.getItem("payoutTime");
$scope.payoutAmount = localStorage.getItem("payoutAmount");
var defer = $q.defer();
defer.resolve($scope.ticketPin);
defer.resolve($scope.payoutTime);
defer.resolve($scope.payoutAmount);
defer.promise.then(function () {
$window.print();
})
}]);
have a nice day ;)

Related

How to submit edited data to object in angularJS?

When I press accept button task should be updated with new value which I wrote in input.Sad thing it doesnt work like I want.Do i need to add id`s to array with objects?
or maybe there is some good method to send a object to function.Here`s the code:
<tbody>
<tr ng-repeat="task in tasks">
<td>
<button class="btn btn-danger" ng-click="deleteTask(task)">Delete</button>
<!-- $index-->
</td>
<td>{{task.taskName}}</td>
<td>
<input type="checkbox" ng-model="statusCheck"> </td>
<td style="{{setStyleToTd(statusCheck)}}">{{statusChecker(statusCheck)}}</td>
<td>
<button class="btn btn-primary" ng-click="editTask(task)">Edit</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-offset-8 edit-box" ng-show="editBoxShow">
<form action="" class="form-inline">
<div class="form-group">
<lable>Edit task here:</lable>
<div class="input-group">
<input type="text" class="form-control" ng-model="editTaskInput"> </div>
<button type="button" class="btn btn-success" ng-click="acceptEdit()">Accept</button>
</div>
</form>
</div>
$scope.editTask = function(taskToEdit) {
$scope.editBoxShow = true;
$scope.editTaskInput = taskToEdit.taskName;
}
$scope.acceptEdit = function() {
$scope.editBoxShow = false;
$scope.taskToEdit = $scope.editTaskInput;
}
You can capture the index of your table data while clicking edit button and then update the table data by using this index in acceptEdit function.
$scope.editTask = function (taskToEdit) {
$scope.selectedIndex=$scope.tasks.indexOf(taskToEdit);
$scope.editBoxShow = true;
$scope.editTaskInput = taskToEdit.taskName;
}
$scope.acceptEdit = function () {
$scope.editBoxShow = false;
$scope.tasks[$scope.selectedIndex].taskName=$scope.editTaskInput;
}

jQuery autocomplete not working

I am using jQuery-UI autocomplete on angular controller.
On the server side I have MVC, C# 6.0.
Autocomplete simply doesn't work, nothing shows up. I've checked with debugger how many results are returned from server - results are returned:
But nothing happens on the GUI. No drop down list showed up, nothing. No error in the console.
Here is angular controller / function:
angular.module("calendarDefinitionModule")
.controller("calendarDefinitionController", ["$scope", "$http", function ($scope, $http) {
$scope.UrlDeliveryListPaging = null;
$scope.SearchResults = null;
$scope.SearchDishSemiDishMerc = function (srt) {
if ($(event.currentTarget) === null || $(event.currentTarget).val().length < 3) {
return;
}
var objTrigger = event.currentTarget;
$http({
method: "POST",
url: $scope.UrlDeliveryListPaging,
data: {
cSEARCH_STRING: $(event.currentTarget).val(),
cSEARCH_DISH: srt === 'dish' ? '1' : null,
cSEARCH_SEDI: srt === 'semidish' ? '1' : null,
cSEARCH_MERC: srt === 'merc' ? '1' : null
}
}).then(function success(response) {
if (response.data === null) {
return;
}
$scope.SearchResults = [];
var i;
for (i = 0; i < response.data.length; ++i) {
var iKEY = srt === 'dish' || srt === 'semidish' ? response.data[i]["iDISH_KEY"] : response.data[i]["iMERC_KEY"];
var item =
{
iDISH_KEY: response.data[i]["iDISH_KEY"],
iMERC_KEY: response.data[i]["iMERC_KEY"],
iKEY: iKEY,
cDICA_NME: response.data[i]["cDICA_NME"],
cDICA_UNI: response.data[i]["cDICA_UNI"],
cSEARCH_RESULT: response.data[i]["cDICA_NME"] + " ID: " + iKEY
}
$scope.SearchResults.push(item);
}
$(objTrigger).autocomplete({
source: $scope.SearchResults,
select: function (event, ui) {
$(objTrigger).val(ui.item.cSEARCH_RESULT);
$(objTrigger).parent().parent().find("#inputDish_ID").val(ui.item.iKEY);
$(objTrigger).parent().parent().find("inputDish_UNI").val(ui.item.cDICA_UNI);
}
});
}, function failure() {
alert("Napaka pri iskanju!");
})
}
}
On the server side I've included:
ScriptBundle scriptsControllerDefinition = new ScriptBundle("~/scripts/ControllerDefinition");
scriptsControllerDefinition.Include("~/static/scripts/jquery-1.11.0.min.js");
scriptsControllerDefinition.Include("~/static/jquery.ui/js/jquery-ui-1.10.4.custom.js");
scriptsControllerDefinition.Include("~/Scripts/angular.js");
scriptsControllerDefinition.Include("~/Scripts/Angular/CalendarDefinition/calendarDefinitionModule.js");
scriptsControllerDefinition.Include("~/Scripts/Angular/CalendarDefinition/calendarDefinitionController.js");
And here is .cshtml:
<div class="form-group col-sm-12">
<label for="addDish" class="col-sm-2 control-label" style="padding-left:0;">Dodaj jed: </label>
<div class="col-sm-10">
<table id="tblDishes" style="width:100%;border-collapse:collapse;">
<tbody>
<tr id="1">
<td>
<div class="col-sm-2" style="padding-left:0;padding-right:0;">
<input id="inputDish_ID" type="text" class="form-control" placeholder="ID" readonly />
</div>
<div class="col-sm-7" style="padding-right:0;">
<input id="inputDish_NME" type="text" class="form-control" placeholder="Vnesite jed" ng-keyup="SearchDishSemiDishMerc('dish');" />
</div>
<div class="col-sm-1" style="padding-right:0;">
<input id="inputDish_UNI" type="text" class="form-control" placeholder="Enota" readonly />
</div>
<div class="col-sm-1" style="padding-right:0;">
<input id="inputDish_QUA" type="text" class="form-control bfh-number" placeholder="Količina" />
</div>
<div class="col-sm-1" style="padding-right:0;">
<span class="glyphicon glyphicon-plus add-new-dish pull-left" style="font-size:18px;color:green;cursor:pointer;padding-top:1px;"></span>
<span class='glyphicon glyphicon-trash delete-dish pull-right' style='font-size:18px;color:red;cursor:pointer;padding-top:1px;'></span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div><br />

AngularJS: pass perameter to $location.path

I suspect what I'm trying to do is very simple, I'm new to Angular so some obvious practices sort of go over my head. I'm having trouble accessing the show view (sorry, I'm coming to angular from Rails, so I still think in those terms a little bit) for my Acts resource. The view renders fine, but it isn't displaying the data I would like. I suspect the template isn't receiving the $scope.act variable I'm defining in the controller. When I use console.log in the controller, I can see that the variable contains all the data I want to use. I assume I have to do something to pass the variable as a parameter to the template, but I'm not sure how I'd do that.
Here's my code:
app.js
$(document).on('page:load', function() {
return $('[ng-app]').each(function() {
var module;
module = $(this).attr('ng-app');
return angular.bootstrap(this, [module]);
});
});
var snowball_effect = angular.module('snowball_effect', [
'templates',
'ngRoute',
'ngResource',
'controllers'
]);
snowball_effect.config([
'$routeProvider', function($routeProvider) {
return $routeProvider
.when('/', {
templateUrl: "static_pages/templates/index.html",
controller: 'StaticPagesController'
})
.when('/acts/index', {
templateUrl: "acts/templates/index.html",
controller: 'ActsController'
})
.when('/acts/:id', {
templateUrl: "acts/templates/show.html",
controller: 'ActsController'
});
}
]);
var controllers = angular.module('controllers', []);
ActsController.js
controllers = angular.module('controllers');
controllers.controller('ActsController', [
'$scope',
'$routeParams',
'$location',
'$resource',
function($scope,$routeParams,$location,$resource) {
var Act = $resource('/acts/:actId', {
actId: "#id",
format: 'json'
}, {
'create': {
method: 'POST'
}
});
$scope.acts = Act.query();
$scope.addAct = function() {
act = Act.save($scope.newAct, function() {
$scope.acts.push(act);
$scope.newAct = '';
});
}
$scope.deleteAct = function(act) {
Act.delete(act);
$scope.acts.splice($scope.acts.indexOf(act), 1);
}
$scope.linkToShowAct = function(act) {
$scope.act = act;
console.log($scope.act);
$location.path('acts/' + act.id);
}
}]);
show.html
<div class="acts-show">
<div class="container" ng-controller="ActsController">
<div class="body">
<h1>
{{act.name}}
</h1>
<p class="act-show-description">
{{act.description}}
</p>
<p class="act-show-inspires">
<strong>Inspires:</strong>
{{act.inspires}}
</p>
Edit
Back
</div>
</div>
</div>
index.html
<div class="actions_body">
<div class="container">
<h2>Listing Actions</h2>
<div ng-controller="ActsController" class="body">
<table class="row">
<thead>
<tr>
<th class="col-md-2 col-md-offset-1 active">
<label>Name</label>
</th>
<th class="col-md-4">Description</th>
<th class="col-md-2">Inspires</th>
<th colspan="2" class="col-md-2">Modify</th>
</tr>
</thead>
<tbody ng-repeat="act in acts">
<td class="col-md-offset-1 col-md-2">{{act.name}}</td>
<td class="col-md-4">{{act.description}}</td>
<td class="col-md-2">{{act.inspires}}</td>
<td>Edit</td>
<td><button ng-click="deleteAct(act)">Delete</a></button>
</tbody>
</table>
<br>
<button ng-click="newActShow=true">New Action</button>
<button ng-click="newActShow=false">Hide</button>
<div ng-show="newActShow" id="newAct">
<div class="row">
<form class="form-inline" ng-submit="addAct()">
<div class="col-md-3 form-group">
<label for="newActname">Name</label>
<input type="text" ng-model="newAct.name" id="newActname" placeholder="Name" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<label for="newActdescription">Description</label>
<input type="textarea" ng-model="newAct.description" id="newActdescription" placeholder="Description" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<label for="newActinspires">Inspires</label>
<input type="number" ng-model="newAct.inspires" id="newActinspires" placeholder="Inspires" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<input type="submit" value="+" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
try $locationChangeStart in order to make sure your value is set to the scope variable before the state actually changes and the route happens, even if you put the $location.path('acts/' + act.id); before setting the variable, there is no guarantee that the value will be set before the state change (the actual routing).
I would prefer (a more safe value setting method) using a promise for example ..

How can i check radio button by default?

On page load i want to show below radio button selected by default i used html attribute but its not working. So on page load I want to show all process radio button checked by default. Is there any other way to achieve this task?
radio.html
<div class="panel panel-default">
<div class="panel-heading">View/Search Inventory</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterOptions"
k-ng-model="kfilter" ng-model="filter" ng-change="onChange()"></select>
</div>
<div ng-show="filter=='PROCESS'" ng-init="search.showCriteria='allProcess';onChange()">
<div class="col-md-7">
<label class="radio-inline" for="allProcess"> <input
type="radio" name="optionsRadios1" ng-value="'allProcess'"
id="allProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show All Processes
</label> <label class="radio-inline" for="ratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'ratedProcess'"
id="ratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Rated Processes
</label> <label class="radio-inline" for="unratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'unratedProcess'"
id="unratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unrated Processes
</label>
</div>
</div>
<div ng-show="filter=='RISK'">
<div class="col-md-7">
<label class="radio-inline" for="allRisk"> <input
type="radio" name="optionsRadios1" ng-value="'allRisk'"
id="allRisk" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Risks
</label> <label class="radio-inline"> <input type="radio"
name="optionsRadios1" ng-value="'unalignedRisk'"
ng-model="search.showCriteria" ng-change="selectSearchType()">
Show Unaligned Risks
</label>
</div>
</div>
<div ng-show="filter=='CONTROL'">
<div class="col-md-7">
<label class="radio-inline" for="allControl"> <input
type="radio" name="optionsRadios1" ng-value="'allControl'"
id="allControl" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Controls
</label> <label class="radio-inline" for="unalignedControl"> <input
type="radio" name="optionsRadios1" ng-value="'unalignedControl'"
id="unalignedControl" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unaligned Controls
</label>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" ng-click="search(0)">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
<div class="row">
<!--<label for="filterBy" class="col-md-1">Filter by: </label>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'" k-option-label="'Select'"
k-data-value-field="'value'" k-data-source="filterByOptions"
k-ng-model="kfilterBy" ng-model="filterBy" style="width: 100%"></select>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterByValues" k-option-label="'Select'"
k-ng-model="kfilterByValue" ng-model="filterByValue" style="width: 100%"></select>
</div> -->
<div class="col-md-3">
<a href="" ng-show="!showAdvance" ng-click="advanceFilter()">Advanced
Search</a> <a href="" ng-show="showAdvance" ng-click="advanceFilter()">Basic
Search</a>
<!-- <button ng-show="!showAdvance" class="btn btn-default" type="button" ng-click="search()">Go</button> -->
</div>
</div>
<form role="form" name="formTimeLine" kendo-validator="validator"
k-options="myValidatorOptions">
<div ng-show="showAdvance">
<div class="clone" ng-repeat="input in inputs">
<br />
<div class="row">
<div class="col-md-1">
<a ng-if="inputs.length < searchOptions.length"
class="add col-md-1" name="addnumadd" ng-click="add($index)"> </a>
<a ng-if="inputs.length >1" class="delete col-md-1"
name="deletenumadd" ng-click="remove($index)"> </a>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-option-label="'Select'" k-data-value-field="'value'"
k-data-source="searchOptions" name="searchBy-{{$index}}"
ng-model="input.searchBy"
data-required-msg="Please select the value"
ng-change="clearPreviousValue({{$index}})" data-duplicate=""
style="width: 100%" required></select>
</div>
<div class="col-md-3">
<input type="text" class="form-control"
ng-model="input.searchValue" placeholder="Enter search item"
ng-maxlength="256" name={{$index}}>
</div>
<div class="col-md-4">
<input type="radio" name={{$index}} value="exactMatch"
ng-model="input.exactMatch" data-requiredCheckbox=""> Exact
Match <input type="radio" name={{$index}} value="contains"
ng-model="input.exactMatch" data-requiredCheckbox=""> Contains
<span class="k-invalid-msg" data-for={{$index}}></span>
</div>
</div>
</div>
</div>
</form>
</div>
<div id="outergrid" class="row">
<ng-include src="gridInclude"></ng-include>
</div>
</div>
radio.js
$scope.processSearchOptions = processSearchOptions;
$scope.riskSearchOptions = riskSearchOptions;
$scope.controlSearchOptions = controlSearchOptions;
$scope.filterByOptions = filterByOptions;
$scope.filterByValues = filterByValues;
$scope.searchOptions = processSearchOptions;
$scope.onChange = function () {
var value = $scope.filter;
$scope.postArgs.page = 1;
if (value === 'PROCESS') {
$scope.search.showCriteria = 'allProcess';
$scope.searchOptions = processSearchOptions;
$scope.gridInclude = 'views/viewAll/processGrid.html';
}
if (value === 'RISK') {
$scope.search.showCriteria = 'allRisk';
$scope.searchOptions = riskSearchOptions;
$scope.gridInclude = 'views/viewAll/riskGrid.html';
}
if (value === 'CONTROL') {
$scope.search.showCriteria = 'allControl';
$scope.searchOptions = controlSearchOptions;
$scope.gridInclude = 'views/viewAll/controlGrid.html';
}
$scope.showAdvance = false;
$scope.clearAdvFilter();
$scope.postArgs = {
page: 1
};
};
//initialize process grid
initializeGrid('process');
$scope.processGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.processGridColumns);
$scope.processInnerGridOptions = viewSearchInvService.getInnerProcessGrid;
//initialize risk grid
initializeGrid('risk');
$scope.riskGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.riskGridColumns);
$scope.riskInnerGridOptions = viewSearchInvService.getInnerRiskGrid;
//initialize control grid
initializeGrid('control');
$scope.controlGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.controlGridColumns);
$scope.controlInnerGridOptions = viewSearchInvService.getInnerControlGrid;
$scope.ProcessEditHandler = function (id) {
ViewEditPrcsService.saveProcessId(id);
};
$scope.RiskEditHandler = function (id) {
ViewEditRiskService.saveRiskId(id);
};
$scope.advanceFilter = function () {
if ($scope.showAdvance) {
$scope.clearAdvFilter();
$scope.showAdvance = false;
} else {
$scope.showAdvance = true;
}
};
$scope.clearAdvFilter = function () {
$scope.inputs = [];
$scope.inputs.push(getNewObject());
};
$scope.search = function () {
if ($scope.validator.validate() || !$scope.showAdvance) {
searchCriteria(1);
searchFlag = true;
if ($scope.filter === 'PROCESS') {
$scope.search.process.dataSource.read();
}
if ($scope.filter === 'RISK') {
$scope.search.risk.dataSource.read();
}
if ($scope.filter === 'CONTROL') {
$scope.search.control.dataSource.read();
}
}
};
$scope.selectSearchType = function () {
$scope.clearAdvFilter();
$scope.showAdvance = false;
$scope.search();
};
$scope.add = function () {
$scope.inputs.push(getNewObject());
};
$scope.remove = function (index) {
$scope.inputs.splice(index, 1);
};
$scope.myValidatorOptions = {
rules: {
duplicate: function (input) {
return checkDuplicates(input.val(), input[0].name);
},
requiredCheckbox: function (input) {
return !(input[0].type === 'radio' && !$scope.inputs[input[0].name].exactMatch && !$scope.inputs[input[0].name].contains);
}
},
messages: {
duplicate: 'Option already selected. please select another option',
requiredCheckbox: 'Operator is required'
}
};
$scope.clearPreviousValue = function (index) {
$scope.inputs[index].searchValue = '';
};
});
Without knowing more about the specifics of when you want this checked, apply the following using ngChecked. In this case, checked if true, but this can be any expression
ng-checked="true"
JSFiddle Link
In response to your updated code, you could leverage ngInit on your parent <div> for defaulting one radio button in a group. Note for isolating the direct issue I have slimmed down most of this markup
<div ng-init="search.showCriteria='allProcess'">
Updated JSFiddle Link
You need to make sure your model is set to the value of the radio box.
$scope.search.showCriteria = 'allProcess'
As a side node, you don't need to be using ng-value here. You could use just use value="allProcess" because ng-value is only needed for Angular expressions, not plain strings.

Load data from Database to DropDownList using Knockout

I'm creating editing a variable length list using knockout.
When I click Add Button, it will add a DropDownList and a TextBox to the screen. I've successfully load the data from database to DropDownList, but it always populating the data every time I clicked Add Button.
Code:
<div class="form-horizontal" data-bind="with: purchaseOrder">
<h4>Purchase Order</h4>
<hr />
<div class="form-group">
<label class="control-label col-md-2" for="PurchaseOrderDate">PO Date</label>
<div class="col-md-10">
<input class="form-control" data-bind="value: PurchaseOrderDate" placeholder="Purchase Order Date" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="InvoiceNo">Invoice No</label>
<div class="col-md-10">
<input class="form-control" data-bind="value: InvoiceNo" placeholder="Invoice No" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Memo">Memo</label>
<div class="col-md-10">
<input class="form-control" data-bind="value: Memo" placeholder="Enter Memo" />
</div>
</div>
</div>
<h4>Details</h4>
<hr />
<table class="table">
<thead>
<tr>
<th>Item Name</th>
<th>Qty Order</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: purchaseOrderDetails">
<tr>
<td>
<select class="form-control" data-bind="options: AX_INVENTSUMs, optionsText: 'ITEMNAME', optionValue: 'ITEMID'"></select>
</td>
<td>
<input class="form-control" data-bind="value: QuantityOrder" placeholder="Enter Quantity Order">
</td>
<td>
<a class="btn btn-sm btn-danger" href='#' data-bind=' click: $parent.removeItem'>X</a>
</td>
</tr>
</tbody>
</table>
<p>
<button class="btn btn-sm btn-primary" data-bind='click: addItem'>Add Item</button>
</p>
#section Scripts {
#Scripts.Render("~/bundles/knockout")
<script>
$(function () {
var PurchaseOrder = function (purchaseOrder) {
var self = this;
self.PurchaseOrderID = ko.observable(purchaseOrder ? purchaseOrder.PurchaseOrderID : 0);
self.PurchaseOrderDate = ko.observable(purchaseOrder ? purchaseOrder.PurchaseOrderDate : '');
self.InvoiceNo = ko.observable(purchaseOrder ? purchaseOrder.InvoiceNo : '');
self.Memo = ko.observable(purchaseOrder ? purchaseOrder.Memo : '');
};
var PurchaseOrderDetail = function (purchaseOrderDetail, items) {
var self = this;
self.PurchaseOrderDetailID = ko.observable(purchaseOrderDetail ? purchaseOrderDetail.PurchaseOrderDetailID : 0);
self.PurchaseOrderID = ko.observable(purchaseOrderDetail ? purchaseOrderDetail.PurchaseOrderDetailID : 0);
self.ItemID = ko.observable(purchaseOrderDetail ? purchaseOrderDetail.ItemID : 0);
self.QuantityOrder = ko.observable(purchaseOrderDetail ? purchaseOrderDetail.QuantityOrder : 0);
self.QuantityBonus = ko.observable(purchaseOrderDetail ? purchaseOrderDetail.QuantityBonus : 0);
self.AX_INVENTSUMs = ko.observableArray(items);
};
var PurchaseOrderCollection = function () {
var self = this;
self.purchaseOrder = ko.observable(new PurchaseOrder());
self.purchaseOrderDetails = ko.observableArray([new PurchaseOrderDetail()]);
self.CashedArray = ko.observableArray([]);
$.getJSON("/AX_INVENTSUM/GetAX_INVENTSUMs", null, function (data) {
var array = [];
$.each(data, function (index, value) {
array.push(value);
});
self.CashedArray(array);
});
self.addItem = function () {
self.purchaseOrderDetails.push(new PurchaseOrderDetail(null, self.CashedArray));
};
self.removeItem = function (purchaseOrderDetail) {
self.purchaseOrderDetails.remove(purchaseOrderDetail);
};
};
ko.applyBindings(new PurchaseOrderCollection());
});
</script>
}
As you can see in the code above, how to make this occurs only once a time?
You must cache your list somewhere. I prefer to do it in something like parent view model. See bellow.
var OrderList = function(){
var self = this;
...
self.CashedArray = ko.observableArray(new Array());
$.getJSON("/AX_INVENTSUM/GetAX_INVENTSUMs", null, function (data) {
var array = [];
$.each(data, function (index, value) {
array.push(value);
});
self.CashedArray(array);
});
self.AddButtonClick = function (){
var orderDetails = new PurchaseOrderDetail(self.CashedArray());
};
};
var PurchaseOrderDetail = function (items) {
var self = this;
...
self.AX_INVENTSUMs = ko.observableArray(items);
};

Categories