Adnan Ali Adnan Ali - 2 years ago 594
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 Source

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


$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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download