在$ watch - angular中获取已更改模型的索引

时间:2014-03-28 09:50:28

标签: javascript angularjs

我正在观看使用$ watch(“模型”)进行任何更改的一系列员工。我想知道正在修改的数组中元素的索引。我怎样才能做到这一点?

HTML

<input type="text" ng-model="employee.value" />

JS

$scope.employees = [
    {
      'value' : 'Tim'
    },
    {
      'value' : 'John'
    },
    {
      'value' : 'Bill'
    },
    {
      'value' : 'John'
    }
];



$scope.$watch("employees", function(newValue, oldValue) {
      console.log(newValue); //newValue shows all the 4 objects..
      //how to get the index of the changed object ?
},true);

Plnkr - http://plnkr.co/edit/qj5zwIHVZXFLCRk9BG3U?p=preview

1 个答案:

答案 0 :(得分:2)

您必须手动进行比较。

这样的事情:

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);

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