有没有办法将监视添加到非作用域变量。我想向局部变量添加一个监视。我有这样的东西
function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
var vm = this;
vm.manufacturers = [];
vm.projects = [];
vm.asset_types = [];
vm.ch_group_uniq = 'none';
}
这里有没有办法将watch添加到vm.ch_group_uniq? 我知道如何使用范围变量来完成它,但我有一些场景,我必须检查许多复杂的变量。
最佳答案
好吧,您可以通过传递函数作为第一个参数来轻松添加对任何东西的监视:
$scope.$watch(function watchFunction(scope) {
return vm.ch_group_uniq
}, handler)
需要考虑的一些事情:如果没有任何变化,watchFunction
必须返回相同的值。这可能会导致一些问题,例如,返回某些数组操作的结果:[1,2,3].filter(...)
将始终返回一个新数组,并导致无休止的$digest
循环。另请注意 $scope.$watch
的第三个参数,它指示在比较值时是否使用恒等比较或 angular.equals
。 (查看文档以获取更多信息 - https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch )
但是,您的具体问题似乎是尝试使用 controllerAs
和自定义 $watch
-es。有一个非常方便的库专门解决了这个问题:https://github.com/christopherthielen/angular-360-no-scope
关于javascript - 在 angularjs 中添加非作用域变量的监视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29643349/