mindparse mindparse - 14 days ago 8
AngularJS Question

scope.$watch within a controller not firing

I am using controllerAs syntax like so:

.state('operators', {
url: '/operators',
templateUrl: 'app/features/operators/operators.html',
controller: 'OperatorsController',
controllerAs: 'vm'
})


And have a variable in my controller
vm.selectedOperators
which I want to watch for changes on:

var vm = this;
vm.selectedOperators = [];


$scope.$watch(function() {
return vm.selectedOperators;
}, function(current) {
console.log(current.length);
});


In the view, an expression is used to show the count of items in the variable.

{{vm.selectedOperators.length}} item selected


This variable gets updated from elsewhere (Its being used by a multi-select table directive I have written which is used on the same view) and I see this expression updating fine in the view.

The problem is my watcher in the controller doesn't fire after the variable gets initialised, and I am not sure why.

Can anyone offer any help?

Thanks

UPDATE

I should have mentioned, I have already tried using the expression equivalent like so:

$scope.$watch('vm.selectedOperators', function (current){
console.log(current);
});


But this still does not fire for me

Answer

Concept: There is an optional third argument to the $watch function - objectEquality

$watch(watchExpression, listener, [objectEquality]);

You must set it to true when you are trying to watch an object otherwise angular will only match the reference of both the objects. By setting it true angular compares the old object and new using angular.equals

Read more about it here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

$scope.$watch(function() {
    return vm.selectedOperators;
}, function(current) {
    console.log(current.length);
}, true);