Skip to content Skip to sidebar Skip to footer

Get The Index Of Changed Model In $watch - Angular

I'm watch a array of employees for any change using $watch('model'). I want to know the index of the element in the array which is being modified. How can I achieve this ? HTML <

Solution 1:

You will have to do the comparison manually.

Something like this:

var previous = [];

var updatePrevious = function(newPrevious) {
  angular.copy(newPrevious, previous);
};

updatePrevious($scope.employees);

$scope.$watch("employees", function(newValue, oldValue) {
  if (newValue !== oldValue) {
    for (var i = 0; i < newValue.length; i++) {

      if (angular.equals(newValue[i], previous[i])) continue;

      var changedEmployee = newValue[i];
      console.log('Changed employee:', changedEmployee);

      var index = newValue.indexOf(changedEmployee);
      console.log('Index:', index);

      updatePrevious(newValue);
    }
  }
}, true);

Demo:http://plnkr.co/edit/MF8ANC83yXaBYevUNzAm?p=preview

Post a Comment for "Get The Index Of Changed Model In $watch - Angular"