【问题标题】:Angular Watch Triggered if newValue changes如果 newValue 发生变化,则触发 Angular Watch
【发布时间】:2015-01-02 18:47:36
【问题描述】:

我想根据其他值重复更改值。我做了一块手表,但问题是,如果我改变手表内的 newValue,手表会再次触发。

有没有办法解决这个问题

我的手表:

 $scope.$watch('objlist', function(newValue, oldValue) {
    $scope.counter += 1;
    for (var count = 0; count < newValue.length; ++count) {
      if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value1 != oldValue[count].value1)) {
        newValue[count].value3 = newValue[count].value1 * newValue[count].value2;
        newValue[count].value3 = Number(newValue[count].value3).toFixed(2);

      }
      if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value3 != oldValue[count].value3)) {
        newValue[count].value1 = newValue[count].value3 / newValue[count].value2;
        newValue[count].value1 = Number(newValue[count].value1).toFixed(2);

      }
    }
  }, true);

我已经包含了一个 plunker 来告诉你我的意思。

plunker

如您所见,如果您更改字段 1 或 3 的值,它会自动将 2 添加到计数器并将两者都设置为 toFixed(2)。这使得编辑字段变得困难。

我们使用角度 1.2.25

【问题讨论】:

  • 只是一个提示,但您可以将 typeof newValue[count] != "undefined" 替换为 newValue[count] 。它也应该这样做。测试一个未定义的就等于说假
  • 由于您在 $watch 中将最后一个参数作为true,这意味着手表是深度对象手表。您无法更改正在监视的对象。
  • 他可以为列表的每个元素添加一个手表,分开。如果他不知道元素的数量,当然不能使用。
  • 并且元素的数量可以改变,不幸的是这是不可能的
  • @Chandermani 我知道我深入观察了对象,但这是检测列表中对象属性变化所必需的。

标签: angularjs angularjs-ng-repeat watch


【解决方案1】:

你可以使用一个带有条件的小技巧。

例如:

$scope.watchActivated = true;

$scope.$watch('objlist', function(newValue, oldValue) {
    if ( $scope.watchActivated ) {
$scope.watchActivated = false;
   $scope.counter += 1;
  for (var count = 0; count < newValue.length; ++count) {
  if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value1 != oldValue[count].value1) )
{
   newValue[count].value3 =  newValue[count].value1 * newValue[count].value2;
  newValue[count].value3 = Number(newValue[count].value3).toFixed(2);

}
  if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value3 != oldValue[count].value3) )
{
     newValue[count].value1 =  newValue[count].value3 / newValue[count].value2;
  newValue[count].value1 = Number(newValue[count].value1).toFixed(2);

}
}
$scope.watchActivated = true;
}
}, true);

远非优雅,但它应该可以工作。 小心代码可能不太好,我只是做了一个快速编辑。

【讨论】:

  • 不幸的是它不起作用。这是因为第二个手表在第一个手表完成之前不会运行,所以第二次 watchActivated 也始终为真。
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 2017-05-23
  • 2014-12-31
  • 2015-09-24
  • 1970-01-01
  • 2014-09-22
相关资源
最近更新 更多