Checkbox checked not updating on delete, its updating the second time - angularjs

i have a code like this:
<body ng-app="UserManagement" ng-controller="UserManagementController">
<h3>to do</h3>
<form ng-submit="addtodo();">
<table>
<tr><td colspan="2"><input type="checkbox" ng-model="employees.todo" /></td></tr>
<tr><td colspan="2">{{remng()}} of {{actuallength}} remaining</td></tr>
<tr ng-repeat="emp in employees">
<td><input type="checkbox" ng-model="emp.todo" /></td>
<td>{{emp.name}}</td>
</tr>
<tr>
<td><input type="text" ng-model="addemp" /></td>
<td><input type="button" value="Add" ng-click="addemps()"/></td>
</tr>
<tr>
<td><input type="button" value="Delete" ng-click="deleteemps();"/></td>
</tr>
</table>
</form>
</body>
here i am making simple add, delete operation of a list of employees. In the delete operation, when i click delete without checking any checkbox, the items with existing checked checkboxes are deleted, but when i click any checkbox and press delete, the clicked checkbox is not deleted this time, but when i click delete second time, it deletes.
Js code:
var app = angular.module("UserManagement", []);
//Controller Part
app.controller("UserManagementController", function($scope, $http) {
$scope.employees = [
{name:'Abhinav',todo:true},
{name:'Amit', todo:false},
{name:'Raghav',todo:true},
{name:'Sumit', todo:false},
{name:'Ashwani',todo:true},
{name:'Mihir', todo:false},
]
$scope.totalsel = $scope.employees.length;
$scope.actuallength = $scope.totalsel;
alert($scope.actuallength);
//$scope.addtodo = function(){}
//alert("ddd");
$scope.deleteemps = function(){
//alert($scope.employees.name);
$scope.deleted_emps = [];
//alert("in foreach: "+$scope.employees[2].todo);
angular.forEach($scope.employees, function(todos, index) {
//alert(todos.todo);
//alert(todos.name);
if(todos.todo){
// alert(index)
var deletednames = todos.name;
// var deletedtodo = todos.todo;
//$scope.deleted_emps.push(deletednames)
// alert(deletednames);
$scope.deleted_emps.push({name:todos.name, todo:todos.todo});
//var abc=angular.toJson($scope.deleted_emps);
// alert(index);
//console.log(angular.toJson(todos.name));
console.log("hiii: "+$scope.deleted_emps.name);
var indx;
for (var i=0; i<$scope.deleted_emps.length; i++) {
console.log("iii: "+$scope.deleted_emps[i].name);
console.log("i: "+$scope.employees[index].name);
//console.log($scope.employees[index].name.indexOf($scope.deleted_emps[i].name));
indx = $scope.employees[index].name.indexOf($scope.deleted_emps[i].name);
// alert(indx);
if (indx > -1) {
// alert(indx);
//$scope.employees.splice()
$scope.employees.splice(index, 1);
}
}
/* var indx;
for (var i=0; i<array2.$scope.deleted_emp; i++) {
indx = array1.indexOf(array2[i]);
if (indx > -1) {
array1.splice(indx, 1);
}
}
*/
}
$scope.actuallength = $scope.totalsel;
})
}
});
I am using angular js 1.6.1 . Thanks in advance.

I've made a fiddle based on your codes.
Add and Delete Employees
Sample code of mine is like this.
$scope.deleteEmp = function(){
var slicedEmps = [];
angular.forEach($scope.employees, function(e){
if(!e.isChecked){
slicedEmps.push(e);
}
});
$scope.employees = slicedEmps;
};
What I suggested is making new array instead of using 'splice'.
I hope this fiddle can help you. :)

Related

Push and splice into array when checkall and checkbox is checked in angularjs

I am trying to push and splice the elements based on checkall, single checkbox clicked, my problem is I am getting a list from angularjs post request and displayed it using ng-repeat I have given provision to enter some text in a new column along with ng-repeat data. Now based on the user selection of checkall or single checkbox clicked I am pushing the data into array. Here I am able to push the data when the user clicked on single checkbox, but when the user clicked on chekall checkbox 0, 1 are pushing the array instead of textbox value. Any help will be greatly appreciated.
Html
<table class='reportstd' align='center' width='80%'>
<tr class='trdesign'>
<td>
<input type="checkbox" name="checkAll" id="all" data-ng-model="checkedAll" data-ng-change="toggleCheckAll()" />
</td>
<td> Sl No</td>
<td> RO No.</td>
<td> Truck No.</td>
</tr>
<tr data-ng-repeat="user in RosList">
<td> <input type="checkbox" value="{{user.do_ro_no}}" data-ng-model="user.checked" data-ng-change="modifyArrayToPost(user,truck_no[$index])" /> </td>
<td>{{$index + 1}}</td>
<td>{{user.do_ro_no}}</td>
<td><input type='text' data-ng-model="truck_no[$index]" id="truck_no_{{$index}}" name="truck_no_{{$index}}" value=""></td>
</tr>
</table>
<table>
<tr>
<td colspan='2'><input type="submit" id="btn_submit" name='sea' value='Search' data-ng-submit="postROs(arrayToPost)" /></td>
</tr>
</table>
Angularjs
$scope.arrayToPost = [];
$scope.toggleCheckAll = function() {
if ($scope.checkedAll) {
angular.forEach($scope.RosList, function(user, truckno) {
user.checked = true;
$scope.modifyArrayToPost(user, truckno);
});
} else {
angular.forEach($scope.RosList, function(user, truckno) {
user.checked = false;
$scope.modifyArrayToPost(user, truckno);
});
}
}
$scope.modifyArrayToPost = function(user, truckno) {
if (user.checked && truckno != null && $scope.arrayToPost.indexOf(user.do_ro_no) == -1) {
$scope.arrayToPost.push(user.do_ro_no, truckno);
} else if (!user.checked) {
$scope.arrayToPost.splice($scope.arrayToPost.indexOf(user.do_ro_no, truckno), 2);
}
}
$scope.$watch('RosList', function() {
var allSet = true;
var allClear = true;
angular.forEach($scope.RosList, function(user, truckno) {
if (user.checked) {
allClear = false;
} else {
allSet = false;
}
});
var checkAll = $element.find('#all');
checkAll.prop('indeterminate', false);
if (allSet) {
$scope.checkedAll = true;
} else if (allClear) {
$scope.checkedAll = false;
} else {
$scope.checkedAll = false;
checkAll.prop('indeterminate', true);
}
}, true);
$scope.RosList = [
{do_ro_no: "217PALV000201898", slno: 1, },
{do_ro_no: "317PALV000201898", slno: 2, }
]
truck_no model is not coming from RosList.
You should initialize truck_no in your controller as $scope.truck_no = [] in order to access the values, and in your $scope.toggleCheckAll function change $scope.modifyArrayToPost(user, truckno); to $scope.modifyArrayToPost(user, $scope.truck_no[truckno]);
EDIT:
I've slightly modified your code to handle all cases.
Demo: https://next.plnkr.co/edit/DnzsCFkPQU8ByFZ8
If I understand the issue correctly, I think that the solution is much simpler. The main confusation is that there is not just only one "source of truth" - you hold a state for each row and also all the do_ro_no's.
I suggest to keep track only for each row and calculate the arrayToPost whenever you need.
Like this:
angular.module('app', []).controller('ctrl', ($scope, $element) => {
$scope.truck_no = [];
$scope.RosList = [{
do_ro_no: "217PALV000201898",
slno: 1,
},
{
do_ro_no: "317PALV000201898",
slno: 2,
}
];
$scope.getTruckNo = () => {
return $scope.truck_no.filter((t, index) => {
return $scope.RosList[index].checked;
});
}
$scope.getArrayToPost = () => {
return $scope.RosList
.filter(ros => ros.checked)
.map(ros => ros.do_ro_no);
}
$scope.arrayToPost = [];
$scope.toggleCheckAll = function() {
if ($scope.checkedAll) {
//angular.forEach($scope.RosList, function(user, truckno) {
// user.checked = true;
// $scope.modifyArrayToPost(user, truckno);
//});
$scope.RosList.forEach(ros => ros.checked = true);
} else {
//angular.forEach($scope.RosList, function(user, truckno) {
// user.checked = false;
// $scope.modifyArrayToPost(user, truckno);
//});
$scope.RosList.forEach(ros => ros.checked = false);
}
}
//$scope.modifyArrayToPost = function(user, truckno) {
// if (user.checked && truckno != null && $scope.arrayToPost.indexOf(user.do_ro_no) == -1) {
// $scope.arrayToPost.push(user.do_ro_no, truckno);
// } else if (!user.checked) {
// $scope.arrayToPost.splice($scope.arrayToPost.indexOf(user.do_ro_no, truckno), 2);
// }
//}
//$scope.$watch('RosList', function() {
// var allSet = true;
// var allClear = true;
// angular.forEach($scope.RosList, function(user, truckno) {
// if (user.checked) {
// allClear = false;
// } else {
// allSet = false;
// }
// });
//
// var checkAll = $element.find('#all');
// checkAll.prop('indeterminate', false);
// if (allSet) {
// $scope.checkedAll = true;
// } else if (allClear) {
// $scope.checkedAll = false;
// } else {
// $scope.checkedAll = false;
// checkAll.prop('indeterminate', true);
// }
//}, true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table class='reportstd' align='center' width='80%'>
<tr class='trdesign'>
<td>
<input type="checkbox" name="checkAll" id="all" data-ng-model="checkedAll" data-ng-change="toggleCheckAll()" />
</td>
<td> Sl No</td>
<td> RO No.</td>
<td> Truck No.</td>
</tr>
<tr data-ng-repeat="user in RosList">
<td> <input type="checkbox" value="{{user.do_ro_no}}" data-ng-model="user.checked" data-ng-change="modifyArrayToPost(user,truck_no[$index])" /> </td>
<td>{{$index + 1}}</td>
<td>{{user.do_ro_no}}</td>
<td><input type='text' data-ng-model="truck_no[$index]" id="truck_no_{{$index}}" name="truck_no_{{$index}}" value=""></td>
</tr>
</table>
<table>
<tr>
<td colspan='2'><input type="submit" id="btn_submit" name='sea' value='Search' data-ng-submit="postROs(arrayToPost)" /></td>
</tr>
</table>
<pre>
{{getTruckNo() | json}}
</pre>
</div>
The array is the result of getTruckNo() as you can see in the snippet.

How to Send multiple values from Asp.Net WebApi to Angularjs Controller?

WebApi Controller.. How to send this value to Angularjs controller (bill = q.TotalBill;)? I have send this (return Ok(gridlist);) into JSON form into angularjs controller
public static double bill; // this is static variable on top of a class
[System.Web.Http.Route("api/Products/gridpro/{id}")]
public IHttpActionResult GetGrid(int id)
{
var q = db.products.Find(id);
if (q != null)
{
var check = gridlist.Where(x => x.Id == id).FirstOrDefault();
if (check != null)
{
check.ProductQty += 1;
check.TotalAmount = check.ProductQty * check.ProductRate;
}
else
{
q.ProductQty = 1;
q.TotalAmount = q.ProductQty * q.ProductRate;
gridlist.Add(q);
}
q.TotalBill = gridlist.Sum(x => x.TotalAmount);
foreach (var item in gridlist)
{
item.TotalBill = q.TotalBill;
}
bill = q.TotalBill; //How to send this value to Angularjs controller
return Ok(gridlist);
}
else
{
return NotFound();
}
}
Anagularjs Code: I see all the data into the HTML using this ($scope.gridproducts) but I want to show (bill = q.TotalBill;) this single value into HTML code
$scope.OnProChange = function (Pro) {
var id = Pro.Id;
$http.get("/api/Products/gridpro/" + id).then(function (response) {
console.log(JSON.stringify(response.data))
$scope.gridproducts = response.data;
})
}
HTML code:How I can show total bill value I use {{gridproducts.TotalBill}} this but nothing works.
<tbody>
<tr ng-repeat="item in gridproducts">
<td>
<a class="delete"><i class="fa fa-times-circle-o"></i></a>
</td>
<td class="name">{{item.ProductName}}</td>
<td>{{item.ProductRate}}</td>
<td>
<input class="form-control qty" style="width:50px" onchange="UpdatePurchaseItem('36',this.value)" value="{{item.ProductQty}}">
</td>
<td>{{item.TotalAmount}}</td>
</tr>
<tr></tr>
<tfoot>
<tr>
<th colspan="2"></th>
<th colspan="2"><b>Total</b></th>
<th><b>{{gridproducts.TotalBill}}</b></th>
</tr>
<tr>
<th colspan="2"><b></b></th>
<th colspan="2"><b>Total Items</b></th>
<th><b>25</b></th>
</tr>
</tfoot>
</tbody>
if you want send multiple values to angularjs , you may create complex type for that.
for example,
in c# code
Public Class GridDataModel<T>
{
public T ItemList{get;set;}
public int TotalBill{get;set}
}
then when you return data to js
var gridData=new GridDataModel<products>()
{
ItemList=gridlist,
TotalBill=q.TotalBill
}
return Ok(gridData);
after doing this , you can create another propert for js scope
$http.get("/api/Products/gridpro/" + id).then(function (response) {
console.log(JSON.stringify(response.data))
$scope.gridproducts = response.data.ItemList;
$scope.totalBill = response.data.TotalBill;
})

Inconsistent Data on multiple page printing on a printer

Requirement
To print three(depends on the server response size) pages of print on one button click event.
Stored a barcode image an array, and loop through that array and bind the value to ctrl.barCodeImage. Then call the print service to print each bar code in different page. But it print always three same value that is the last value in the array.
It is a three separate pages with different bar code data in it.
This is the expected response
print 1
print 2
print 3
Current response is inconsistent.
It will come all pages same value , which is the last value in that array.
Implementation Details:
Created an DOM, which will be printed each time with different value assigned to it.
<div id="printThisElement" class="onlyprint" >
<table>
<tr>
<td>{{ ctrl.instCode }}</td>
<td align="center">{{ ctrl.date | dateDisplayFilter}} </td>
</tr>
<tr>
<td colspan="2" align="center"> <img ng-src="data:image/JPEG;base64,{{ctrl.barCodeImage}}"> </td>
</tr>
<tr>
<td colspan="2" align="center">{{ ctrl.user.name }} </td>
</tr>
<tr>
<td >Reg Id: {{ ctrl.regIdLookup }}</td>
<td align="center">{{ ctrl.testName }}</td>
</tr>
</table>
</div>
The print function which is getting called on the button click, added timeout to get assigned all the values on the print div.
vm.print = function() {
var res = [];
var sampleId = [];
var noTest = false;
angular.forEach(vm.gridOptions.data, function(item) {
if (item.sample != null) {
sampleId.push(angular.copy(item.sample.sampleId));
}
})
if(sampleId != null){
UserService.getInstitute(vm.user.instCode).then(function(response) {
vm.instCode = response.data.result.estName;
});
var userServicePromise = UserService.printBarCodes(sampleId);
userServicePromise.then(function(response) {
if (response != null && response.data != null && response.data.result != null) {
response.data.result.forEach(function(entry) {
vm.barCodeImage = angular.copy(entry);
$timeout(function() {
PrintService.printElement("printThisElement");
}, 0);
});
} else {
toaster.error(response.data.message);
}
});
}
}
}
Print Service, which is used to print the DOM.
(function() {
'use strict';
angular.module('app.services')
.factory('PrintService', PrintService);
PrintService.$inject = [];
function PrintService() {
var service = {
printElement: printElement
};
return service;
function printElement(elem) {
var printSection = document.getElementById('printSection');
// if there is no printing section, create one
if (!printSection) {
printSection = document.createElement('div');
printSection.id = 'printSection';
document.body.appendChild(printSection);
}
var elemToPrint = document.getElementById(elem);
// clones the element you want to print
var domClone = elemToPrint.cloneNode(true);
printSection.innerHTML = '';
printSection.appendChild(domClone);
window.print();
window.onafterprint = function() {
printSection.innerHTML = '';
}
};
}
})();
Not able to figure out why it gives inconsistent print data on each time. I guess it might be synchronous issue.
But most of the time it displays the last data in all three page of print.Thanks in advance.
Plunk here https://plnkr.co/edit/jwoC0bNQJ9J92l5S8ZJJ?p=preview
Any HELP ?
I forked your plunker and I use a queue to allow multiple printing
https://plnkr.co/edit/xZpcx6rCAUo9SemUPTt5?p=preview
I have a print function
function print(data) {
var domClone = '<div id="printThisElement" class="onlyprint" >'+
'<table>'+
'<tr> '+
'<td>{{ data.instCode }}</td>'+
'<td align="center">{{ data.date}} </td>'+
'</tr>'+
'<tr> '+
'<td colspan="2" align="center"> <img ng-src="data:image/JPEG;base64,{{data.barCodeImage}}"> </td>'+
'</tr>'+
'<tr> '+
'<td colspan="2" align="center">{{ ctrl.user.name }} </td>'+
'</tr>'+
'<tr> '+
'<td >Reg Id: {{ data.regIdLookup }}</td>'+
'<td align="center">{{ data.testName }}</td>'+
'</tr>'+
'</table>'+
'</div>'
printSection.innerHTML = '';
var scope = $rootScope.$new();
scope.data = data;
var domTemp = $compile(domClone)(scope)[0];
printSection.appendChild(domTemp);
$timeout(function(){
onPrintFinished(window.print());
}, 0);
}
And in PrintElement function i put in queu if printing is in progress :
if(!printInProgress) {
printInProgress = true;
print(data)
}
else {
queue.push(data);
}
At the end of printing run new printing with new data:
function onPrintFinished (printed){
var next = queue.shift();
if(next) {
console.log(next, queue);
$timeout(function() {
print(next);
});
}
else {
printInProgress = false;
}
}
I hope this time you have that you want
The problem is that vm.barCodeImage is set before corresponding PrintService.printElement is actually executed. So the sequence is:
vm.barCodeImage = angular.copy(first entry);
vm.barCodeImage = angular.copy(second entry);
vm.barCodeImage = angular.copy(third entry);
PrintService.printElement("printThisElement");
PrintService.printElement("printThisElement");
PrintService.printElement("printThisElement");
The solution is to modify your code in the following way:
$timeout(function() {
vm.barCodeImage = angular.copy(entry);
PrintService.printElement("printThisElement");
}, 0);
Thanks to that each call PrintService.printElement will use proper data and not the last element in the array.

Mutliplr print functionality return inconsistent data , on changing $timeout value

I want to print a multiple barcode slip, each will have different barcode.
Using a print service to print the div content,
(function() {
'use strict';
angular.module('app.services')
.factory('PrintService', PrintService);
PrintService.$inject = [];
function PrintService() {
var service = {
printElement: printElement
};
return service;
function printElement(elem) {
var printSection = document.getElementById('printSection');
// if there is no printing section, create one
if (!printSection) {
printSection = document.createElement('div');
printSection.id = 'printSection';
document.body.appendChild(printSection);
}
var elemToPrint = document.getElementById(elem);
// clones the element you want to print
var domClone = elemToPrint.cloneNode(true);
printSection.innerHTML = '';
printSection.appendChild(domClone);
window.print();
window.onafterprint = function() {
printSection.innerHTML = '';
}
};
}
})();
Using this print service, will print the slip. Slip data will bind.
var userServicePromise = UserService.printBarCodes(sampleId);
userServicePromise.then(function(response) {
if (response != null && response.data != null && response.data.result != null) {
response.data.result.forEach(function(entry) {
/* $timeout(function() {
vm.barCodeImage = angular.copy(entry);
}, 0);*/
//vm.testName = item.testMast.testName.slice(0, 3);
vm.barCodeImage = angular.copy(entry);
$timeout(function() {
PrintService.printElement("printThisElement");
}, 1);
});
} else {
toaster.error(response.data.message);
}
});
This is the html which will be printed eventually, using DOM element id for printing.
<div id="printThisElement" class="onlyprint" >
<table>
<tr>
<td>{{ ctrl.instCode }}</td>
<td align="center">{{ ctrl.date | dateDisplayFilter}} </td>
</tr>
<tr>
<td colspan="2" align="center"> <img ng-src="data:image/JPEG;base64,{{ctrl.barCodeImage}}"> </td>
</tr>
<tr>
<td colspan="2" align="center">{{ ctrl.user.name }} </td>
</tr>
<tr>
<td >Reg Id: {{ ctrl.regIdLookup }}</td>
<td align="center">{{ ctrl.testName }}</td>
</tr>
</table>
</div>
Expected out put is three slips with different barcode:
7865
7866
7867
Output is three slips with same barcode
7865
7865
7865
some times,
7866
7866
7866
On changing the $timeout(function() value output be like
7865
7865
7866
what can be the reason for this ?
Never ever modify the DOM from inside a service, that's just totally against the whole way Angular works. What you should do instead is create a model of the data (and it's quite alright to create that in the service) and use Angular's templates to render that model in the page.
The reason your code doesn't work is that you are trying to re-use vm.barCodeImage for different images on the page. Angular tracks the changes and will redraw existing parts of the page. That is why you get the same barcode repeated: the different copies each use the same model so they will be the same.
A simple solution is to create an array ofvm.barCodeImages and then just render them in an ng-repeat loop. A better way might be to create a myBarcode directive which uses UserService.printBarCodes to create one barcode in an isolated scope and then your template will look shorter and tidier.

How to call ng-disabled with a function from web service response

The ng-disabled has a function that takes the response from api and two parameters. But it never gets called after the response.
function PermissionController(permissionResource) {
var vm = this;
vm.message = 'Permission';
vm.permissions;
permissionResource.query(function(data) {
vm.permissions = data;
});
vm.isPermissionMissing = function (r, a) {
for(var i = 0; i < vm.permissions.length; i++) {
if(vm.permissions[i].Resource == r && vm.permissions[i].Action == a)
return -1;
}
return 1;
};
}
module.controller("PermissionController", PermissionController);
Then my view has a button to show/hide with ng-disabled.
<button type="submit" class="btn btn-primary btn-block" ng-disabled="isPermissionMissing('account', 'search')">Search</button>
Then a table with ng-repeat
<table class="table">
<thead>
<tr>
<td>resource</td>
<td>action</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="permission in vm.permissions">
<td>{{ permission.Resource }}</td>
<td>{{ permission.Action }}</td>
</tr>
</tbody>
</table>
Problem is by the time the page loads with the api response, it does not call the function in ng-disabled.
I tried the promise then with no luck.
permissionResource.query(function(data) {
vm.permissions = data;
}).$promise
.then(function (result) {
vm.isPermissionMissing = function (r, a) {
for(var i = 0; i < result.length; i++) {
if(result[i].Resource == r && result[i].Action == a)
return -1;
}
return 1;
};
});
The angular documentation shows ngInit being used with ngDisabled.
https://docs.angularjs.org/api/ng/directive/ngDisabled
In your instance I would move the function call to ng-init. Then in the function you need to create a scope variable to set true/false. Let me know if that works for you.
<button type="submit" class="btn btn-primary btn-block" ng-init="isPermissionMissing('account', 'search')" ng-disabled="{{isDisabled}}">Search</button>
vm.isPermissionMissing = function (r, a) {
for(var i = 0; i < vm.permissions.length; i++) {
if(vm.permissions[i].Resource == r && vm.permissions[i].Action == a)
vm.isDisabled = false;
}
vm.isDisabled = true;
};enter code here

Resources