angularjs - 在 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 不要赶上变化。但是所有功能都按我的预期工作。有什么区别?
解决方案
您不能将变量传递给 $watch,因为您只会像任何 JS 函数一样传递变量值:
a = 5; console.log(a);
是一样的console.log(5)
所以this.quantity = 1; $scope.$watch(this.quantity)
是一样的$scope.$watch(1)
,没有意义。
您可以做的是传递变量范围名称:( $scope.$watch('$ctrl.quantity', ...
如果 $ctrl 是您的控制器的引用)
有关详细信息,请参阅
推荐阅读
- android - 点击 2 次 Android Studio 后 Tablayout 不出现
- ruby-on-rails - Rails, Grape - ParamScope 中的请求上下文
- sas - 按SAS变量中的范围删除观察值
- python - Python 多久会出错一次?
- amazon-web-services - AWS i3 与 i2 实例,它们的性能有何不同?
- regex - 带有连字符的字母数字序列无法使用 Go 的正则表达式
- java - 在使用它们影响的数据之前,我是否必须确保在 Java 中手动加载类?
- python - os.replace 在 Windows 上的例外与在 Linux (Ubuntu) 上没有例外
- python - 代码在 Python 中运行后如何让 Chrome 测试浏览器不关闭?
- python - Django - 无法从输入字段中获取值