Reputation: 2276
I'm using Angularjs. I a have table where users can add and update a user list. When someone edits an existing user I'm first removing that user from a scoped array then pushing the updated object.
$.each($scope.users, function (index, value) {
if (value['empId'] == $scope.userToAdd.empId) {
console.log(index);
$scope.users.splice(index, 1);
}
});
$scope.users.push($scope.userToAdd);
Is this the best way to approach this problem? Second issue I'm having is on the line where I splice. Angular is throwing an error that reads:
Error: value is undefined
The element is still removed but this error prevents the push from happening. I have a feeling this has something to do with scope, but can find the answer. Thanks!
Upvotes: 0
Views: 94
Reputation: 42669
The problem with your code is that you are removing from the array while you are iterating over it, which is inconsistent.
What you should do is
Something like
$.each($scope.users, function (index, value) {
if (value['empId'] == $scope.userToAdd.empId) {
userFoundAt=index;
}
});
$scope.users.splice(userFoundAt, 1);
$scope.users.push($scope.userToAdd);
Upvotes: 1