7

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?

1
  • Exactly the same way: $scope.$watchGroup
    – New Dev
    Feb 7, 2015 at 1:47

2 Answers 2

13

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.

0

To make use of #watchGroup using controller as syntax, first you will have to declare your controller in the following way:

app.controller('Controller1', ['$scope', Controller1]);

function Controller1($scope) {
    var vm = this;
    vm.firstName = 'Agustin';
    vm.lastName = 'Cassani';
    vm.newVal = '';
    vm.oldVal = '';

    $scope.$watchGroup(['vm.firstName', 'vm.lastName'], function (newValue, oldValue) {
        vm.newVal = newValue;
        vm.oldVal = oldValue;
    });
}

As you can see, we have made a reference to "this" in the vm variable.

In your application routing configuration, you will have something like this, if you are declaring your controllers on the routes definition, of course:

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider',
  function ($routeProvider) {
      $routeProvider.
        when('/', {
            templateUrl: 'app/views/view1.html',
            controller: 'Controller1',
            controllerAs: 'vm'
        }).
        otherwise({
            redirectTo: '/'
        });
  }]);

Finally, the html of our view will be something like this:

<input type="text" data-ng-model="vm.firstName" />
<input type="text" data-ng-model="vm.lastName"/>
<br/>
<div>
    {{vm.newVal}}
</div>
<div>
    {{vm.oldVal}}
</div>

I.H.I.H (I Hope It Helps!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.