Angularjs $ watchGroup with controller as syntax

Based on the Angular JS style guides I read recently, it seems that the controller-like syntax for Angular J5 controllers is preferable for several reasons.

I saw examples of how to enter $ scope to use special methods like $ watch, $ on, etc.

This example below shows how to successfully use $ watch with the syntax 'controller as':

$scope.$watch(angular.bind(this, function () { return this.name; }), function(value) { console.log('Name change to ' + value); }); 

What I did not find anywhere is how to use $ watchGroup using this similar approach. Does anyone know how to do this?

+6
source share
2 answers

Say a controller has two properties: firstName and lastName . To call a function when any of them changes, use Array of functions as the first argument to $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 newValues is an array containing the new firstName and lastName .

+12
source

To use #watchGroup using a controller as syntax, you will first need to declare your controller as follows:

 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 made a reference to "this" in the vm variable.

In the routing configuration of your application, you will have something like this if, of course, you declare your controllers to determine the routes:

 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 would 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> 

IHIH (hope this helps!)

0
source

Source: https://habr.com/ru/post/982121/


All Articles