If you want to monitor a specific item on the controller instance or any object, using a watcher evaluator function can be very useful. You have the flexibility to return any variable you want.
var vm = this;
//Here, vm represents the cached controller instance.
$scope.$watch(function(){
return vm.propToWatch;
}, function() {
//Do something
}, true);//<-- turn on this if needed for deep watch
Another method is using a bound function to bind the this
context.
$scope.$watch(angular.bind(this, function(){
return this.propToWatch;
//You can simply return the variable here
}), listenerFn);
You can also use the ES5 function.bind:
$scope.$watch((function(){
return this.propToWatch;
}).bind(this), listenerFn);
In the TypeScript environment, the syntax becomes even shorter.
$scope.$watch(()=> this.propToWatch, listenerFn);
Although you can watch the controller alias inside the controller ($scope.watch('ctrlAs.someProp'
), it can lead to a few issues:
It requires knowing the exact alias used for the controller in various places where the controller is implemented, which contradicts the purpose of using controllerAs:'anyVMAlias'
for readability.
When unit testing the controller, you need to ensure the same alias is used, adding an extra step, especially for TDD.
Using a watcher with a watcher function instead of a string reduces the internal steps taken by the angular $parse to convert the expression, as seen in the switch-case of the $parse implementation.