【问题标题】:Angular $watch is not working for arrays and data collectionsAngular $watch 不适用于数组和数据集合
【发布时间】:2015-05-08 15:59:19
【问题描述】:

我需要观察对象列表中的变化,并对变化执行一些操作,但是,Angular $watch 仅在首次创建列表并将初始对象推入其中时触发一次:

$scope.$watch('components', function(newComponents, oldComponents) {
  if (typeof $scope.components !== 'undefined')) {
    return;
  }
  // this alert show only on first change
  alert('change');
});

// only pushing first object triggers the $watch
$scope.components.push({ id: 1, name: 'first component'});
$scope.components.push({ id: 2, name: 'second component'});
$scope.components.push({ id: 3, name: 'third component'});

【问题讨论】:

    标签: arrays angularjs onchange angularjs-watch


    【解决方案1】:

    解决办法是用$watchCollection代替$watch方法:

    $scope.$watchCollection('components', function(newComponents, oldComponents) {
      if (typeof $scope.components !== 'undefined')) {
        return;
      }
      // now this alert will show for each new element added!
      alert('change');
    });
    

    来源:https://code.angularjs.org/1.3.15/docs/api/ng/type/$rootScope.Scope#$watchCollection

    【讨论】:

    • 在示例中,您提供的 $watch 不是由推送触发的 - 您可以删除所有推送并仍然获得一项更改。这是因为 $watch 表达式在每个摘要周期计算一次 - 不是在你更改值之后立即计算。
    【解决方案2】:

    请注意,$watchCollection 仅监视对象/数组的 1 层。在你的情况下这似乎很好。

    要观察更复杂的物体,具有多层次的深度,需要使用带有“true”作为第二个属性的$watch。

    Check out this for a detailed explanation of $watch vs $watchCollection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2016-01-31
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多