mindparse mindparse - 1 year ago 79
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
which I want to watch for changes on:

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

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

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?



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

$scope.$watch('vm.selectedOperators', function (current){

But this still does not fire for me

Answer Source

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) {
}, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download