0

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!

3
  • Instead of putting $scope.users.push($scope.userToAdd); at the last put this code after $scope.users.splice(index, 1); it will solve the problem. Commented Jul 11, 2013 at 10:56
  • u can also use ng-grid directly out of the box check this -> angular-ui.github.io/ng-grid scroll down to Edit On Focus Cell Selection Example, plnkr-> plnkr.co/edit/KJmYbO?p=preview Commented Jul 11, 2013 at 11:02
  • modified ng-grid to suit your need. plnkr.co/edit/cJHgKI?p=preview Commented Jul 11, 2013 at 11:10

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.