在angularjs中的非范围变量上添加监视

Adn*_*Ali 19 javascript angularjs angularjs-directive angularjs-scope

有没有办法将监视添加到非范围变量.我想为本地变量添加一个监视.我有类似的东西

 function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
        var vm = this;
        vm.manufacturers = [];
        vm.projects = [];
        vm.asset_types = [];
        vm.ch_group_uniq = 'none';
}
Run Code Online (Sandbox Code Playgroud)

这里有一种方法可以将监视添加到vm.ch_group_uniq吗?我知道如何使用范围变量,但我有必须检查许多复杂变量的情况.

Sac*_*cho 22

好吧,你可以通过传递函数作为第一个参数轻松添加任何东西:

$scope.$watch(function watchFunction(scope) {
    return vm.ch_group_uniq
}, handler)
Run Code Online (Sandbox Code Playgroud)

需要考虑的一些事项:如果没有任何变化,watchFunction必须返回相同的值.这可能导致一些陷阱,例如,返回一些数组操作的结果:[1,2,3].filter(...)将始终返回一个新数组,并导致无限$digest循环.另请注意第三个参数$scope.$watch,指示是使用身份比较还是angular.equals比较值.(查看文档以获取更多信息 - https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch)

但是,您的具体问题似乎是尝试使用controllerAs和自定义$watch.有一个非常方便的库,专门解决这个问题:https://github.com/christopherthielen/angular-360-no-scope

  • 好的解决方案,但是当变量改变时它不会直接影响监视,除非当前范围有任何其他变化. (3认同)

Pan*_*kar 10

$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);
});
Run Code Online (Sandbox Code Playgroud)

这是参考Todd Motto文章