Book Image

AngularJS Web application development Cookbook

By : Matthew Frisbie
Book Image

AngularJS Web application development Cookbook

By: Matthew Frisbie

Overview of this book

Packed with easy-to-follow recipes, this practical guide will show you how to unleash the full might of the AngularJS framework. Skip straight to practical solutions and quick, functional answers to your problems without hand-holding or slogging through the basics. Avoid antipatterns and pitfalls, and squeeze the maximum amount out of the most powerful parts of the framework, from creating promise-driven applications to building an extensible event bus. Throughout, take advantage of a clear problem-solving approach that offers code samples and explanations of components you should be using in your production applications.
Table of Contents (17 chapters)
AngularJS Web Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Combining watchers with $watchGroup


You might find that multiple model components need to be tied to the same $watch type callback. As of the 1.3 release, AngularJS provides the $watchGroup method that accepts a collection of watch targets in which all the watch targets need to bind to the same callback.

How to do it…

The change event callback parameters can be an ordered array of the current values, followed by an ordered array of the previous values. This is shown here:

(app.js)

angular.module('myApp',[])
.controller('Ctrl', function($scope, $log) {
  $scope.ping = 'pong';
  
  $scope.ding = {
    dong: 'ditch' 
  };
  
  // watch ping and the ding.dong property by reference
  $scope.$watchGroup(['ping', 'ding.dong'], function(newVals, oldVals, scope) {
    // callback logic
    $log.log(newVals, oldVals, scope);
  });
});

(index.html)

<div ng-app="myApp">
  <div ng-controller="Ctrl">
    <input ng-model="ping" />
    <input ng-model="ding.dong" />
  </div&gt...