【问题标题】:Using $watch in angularjs directive, why it works only with function as parameter在 angularjs 指令中使用 $watch,为什么它只适用于函数作为参数
【发布时间】:2019-10-19 05:05:08
【问题描述】:

我正在研究 angularjs 应用程序,但我不明白为什么指令中的 $watch 只能在第一个参数中使用函数时按预期工作。

class PaginationController {
  constructor($scope) {
    "ngInject";
    this.quantity = null;
    this.$scope = $scope;

    $scope.$watch(() => this.quantity, function (newValue, OldValue) {
      console.log('new: ' + newValue);
      console.log('old: ' + OldValue);
    });
  }
}

如果我只是使用 this.quantity 作为第一个参数 $watch 不要赶上变化。但是所有功能都按我的预期工作。有什么区别?

【问题讨论】:

    标签: angularjs angularjs-directive watch


    【解决方案1】:

    您不能将变量传递给 $watch,因为您只会像任何 JS 函数一样传递变量值:

    a = 5; console.log(a); 等同于console.log(5)

    所以this.quantity = 1; $scope.$watch(this.quantity)$scope.$watch(1) 相同,没有任何意义。

    您可以做的是传递变量范围名称:$scope.$watch('$ctrl.quantity', ...(如果 $ct​​rl 是您的控制器的引用)

    有关详细信息,请参阅

    【讨论】:

    • 我会澄清一个事实,它需要在第一个参数中是一个字符串
    猜你喜欢
    • 2020-01-13
    • 2015-07-11
    • 2010-12-25
    • 1970-01-01
    • 2016-12-04
    • 2023-03-09
    • 2013-01-05
    • 2017-07-15
    • 2014-11-28
    相关资源
    最近更新 更多