20

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(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
        var vm = this;
        vm.manufacturers = [];
        vm.projects = [];
        vm.asset_types = [];
        vm.ch_group_uniq = 'none';
}

here is there a way to add watch to vm.ch_group_uniq? I know how it will be done with scope variable but I have scenarios where I have to check many complex variables.

3 Answers 3

23

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

Sign up to request clarification or add additional context in comments.

1 Comment

good solution, but when the variable change it doesn't affect watch directly unless there is any other changes in the current scope.
10

$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

Comments

2

A cleaner syntax using ES6

$scope.$watch(() => {
    return this.thingToWatch;
}, (newVal, oldVal) => {
    // Your code here...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.