首页 > 解决方案 > 在 angularjs 指令中使用 $watch,为什么它只适用于函数作为参数

问题描述

我正在研究 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 不要赶上变化。但是所有功能都按我的预期工作。有什么区别?

标签: angularjsangularjs-directivewatch

解决方案


您不能将变量传递给 $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 是您的控制器的引用)

有关详细信息,请参阅


推荐阅读