【问题标题】:How can I get specific object and its index that was changed from $watch Angular如何获取从 $watch Angular 更改的特定对象及其索引
【发布时间】:2017-06-09 07:12:23
【问题描述】:

我从 API 获取对象数组,每 2 秒更新一次。我有 $watch 正在寻找此数组中的任何更改。我需要知道什么是元素或元素已更改及其索引,以便为这些已更改的元素设置背景颜色。 提前致谢。

$scope.$watch('recentUpdates', function(newValue, oldValue) {
  if(oldValue != newValue && newValue != null){
    $scope.recentUpdates= newValue;
    console.log(newValue)
    setColor(newValue) ;
}else{
    console.log('hey, value is not changed!');
}

});

SetColor 函数需要获取元素的对象和索引才能更新其颜色。

【问题讨论】:

    标签: javascript arrays angular angularjs-directive watch


    【解决方案1】:

    我认为每个周期可能有不止一个变化。因此,您可以循环遍历数组以查找更改。我还假设数组的长度不会改变。

    $scope.$watch('recentUpdates', function(newValue, oldValue) {
      for (var i=0; i < newValue.length; i++) {
        if (newValue[i] !== oldValue[i]) {
          console.log(newValue[i]);
          setColor(newValue[i], i) ;
        }
      }
    });
    

    然后将新值和位置传递给 setColor 函数。我还删除了$scope.recentUpdates= newValue;,因为没有理由这样做。

    如果您愿意,也可以使用 angular.forEach 循环遍历数组。

    【讨论】:

    • 感谢您的回答和解释
    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2021-09-25
    • 2016-02-21
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多