我正在观看使用$ 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);
答案 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);