rross
rross

Reputation: 2276

Updating an element in array

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

Answers (1)

Chandermani
Chandermani

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

  1. Find the index of the user you want to delete (Using some looping construct like $.each)
  2. Splice the element out (outside the loop).
  3. Add it back.

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

Related Questions