获取$ watch中已更改模型的索引-angular [英] Get the index of changed model in $watch - angular

查看:50
本文介绍了获取$ watch中已更改模型的索引-angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在监视一系列使用$ watch("model")进行更改的员工.我想知道正在修改的数组中元素的索引.我该如何实现?

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

<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/qj5zwIHVZXFLCRkk9BG3U?p=preview

推荐答案

您将必须手动进行比较.

You will have to do the comparison manually.

类似这样的东西:

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 =预览

这篇关于获取$ watch中已更改模型的索引-angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆