Based on a bunch of Angular JS style guides I've read recently, it seems that the 'controller as' syntax for Angular JS controllers is preferred for several reasons.
I've seen examples of how to inject $scope in order to use special methods like $watch, $on, etc.
This example below shows how to successfully use $watch with the 'controller as' syntax:
$scope.$watch(angular.bind(this, function () {
return this.name;
}), function(value) {
console.log('Name change to ' + value);
});
What I haven't found anywhere is how to use $watchGroup using this similar approach. Does anyone know how to do this?
Let's say the controller has two properties, firstName
and lastName
. To invoke a function when either of them are changed, use an Array of functions as the first argument of $watchGroup
.
var self = this;
$scope.$watchGroup([function() {
return self.firstName;
}, function () {
return self.lastName;
}], function(newValues, oldValues) {
console.log('Name change to ' + newValues[0] + ' ' + newValues[1]);
});
Note that the newValues
is an Array that contains new firstName
and lastName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With