add watch on a non scope variable in angularjs

落爺英雄遲暮 提交于 2019-12-02 18:16:20
Pankaj Parkar

$watch will not work as normal syntax with controllerAs. You need to bind it to $scope, and then you can watch that variable:

Code

$scope.$watch(angular.bind(this, function (ch_group_uniq) {
  return this.ch_group_uniq;
}), function (newVal, oldVal) {
  console.log('Name changed to ' + newVal);
});

Here is the reference Todd Motto Article

Well, you can easily add a watch for anything by passing a function as the first parameter:

$scope.$watch(function watchFunction(scope) {
    return vm.ch_group_uniq
}, handler)

A few things to consider: watchFunction must return the same value if nothing has changed. This can lead to some gotchas, for example, returning the result of some array operations: [1,2,3].filter(...) will always return a new array, and lead to an endless $digest cycle. Also note the third parameter of $scope.$watch, which indicates whether to use an identity comparison, or angular.equals when comparing the values. (Check out the docs for further information - https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch)

However, your specific problem seems to be trying to use controllerAs and custom $watch-es. There's a very handy library that addresses this issue specifically: https://github.com/christopherthielen/angular-360-no-scope

A cleaner syntax using ES6

$scope.$watch(() => {
    return this.thingToWatch;
}, (newVal, oldVal) => {
    // Your code here...
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!