Javascript 在angularjs中的非作用域变量上添加监视
是否有方法将watch添加到非作用域变量。我想给局部变量添加一个表。我有类似的东西Javascript 在angularjs中的非作用域变量上添加监视,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,是否有方法将watch添加到非作用域变量。我想给局部变量添加一个表。我有类似的东西 function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) { var vm = this; vm.manufacturers = [];
function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
var vm = this;
vm.manufacturers = [];
vm.projects = [];
vm.asset_types = [];
vm.ch_group_uniq = 'none';
}
有没有一种方法可以将手表添加到vm.ch_group_uniq?
我知道如何使用范围变量,但我有一些场景需要检查许多复杂变量。好吧,通过将函数作为第一个参数传递,您可以轻松地添加任何监视:
$scope.$watch(function watchFunction(scope) {
return vm.ch_group_uniq
}, handler)
需要考虑的几件事:watchFunction
必须返回相同的值,如果没有任何更改。这可能导致一些错误,例如,返回某些数组操作的结果:[1,2,3]。筛选器(…)
将始终返回新数组,并导致无休止的$digest
循环。还要注意$scope.$watch
的第三个参数,它指示在比较值时是使用身份比较还是使用angular.equals
。(有关更多信息,请查看文档-)
但是,您的具体问题似乎是试图使用
controllerAs
和自定义$watch
-es。有一个非常方便的库专门解决这个问题:$watch
将不能像正常语法那样使用controllerAs
。您需要将其绑定到$scope
,然后才能查看该变量:
代码
$scope.$watch(angular.bind(this, function (ch_group_uniq) {
return this.ch_group_uniq;
}), function (newVal, oldVal) {
console.log('Name changed to ' + newVal);
});
以下是使用ES6的更清晰语法的参考
$scope.$watch(() => {
return this.thingToWatch;
}, (newVal, oldVal) => {
// Your code here...
});
很好的解决方案,但是当变量更改时,它不会直接影响watch,除非当前范围中有任何其他更改。