Adnan Ali Adnan Ali - 7 months ago 229
Javascript Question

add watch on a non scope variable in angularjs

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.

Answer

$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