add watch on a non scope variable in angularjs

后端 未结 3 1116
自闭症患者
自闭症患者 2021-02-01 06:10

Is there a way to add watch to a non scope variable. I want to add a watch to local variable. I have something like this

 function EditAssetRegistryController(as         


        
3条回答
  •  时光取名叫无心
    2021-02-01 06:24

    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

提交回复
热议问题