Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs $watchGroup with controller as syntax

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?

like image 873
Zach Avatar asked Feb 07 '15 01:02

Zach


1 Answers

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.

like image 104
Shuhei Kagawa Avatar answered Oct 20 '22 14:10

Shuhei Kagawa