Boone Putney bio photo

Boone Putney

Software Development
Random Musings
Austin, Texas

HumanPlanet Soleer

Email LinkedIn Github

Angular.js $watchCollection

We’re building the User Interface for Human Planet Concierge CRM with Angular.js. It’s a great framework, and we’re really enjoying working with it. There’s the whole Angular2 backwards compatibility issue, but only time will tell what comes of that.

Since we’ve been busy coding, it’s been hard to find the time to post recently, but I’ll try to do better. No promises :) Below is a little example of how to perform a shallow watch of an object and fire an event when any of it’s elements change.

Code (within our controller)

1 //watch collection to note differences in old and new users
2 $scope.$watchCollection(function () {
3     return Object.keys(vm.users);
4 },function(newValue, oldValue){
5     //perform any actions necessary on old and new values here
6     console.log(oldValue);
7     console.log(newValue);
8 });

Explanation

the $scope.$watchCollection function takes two parameters:

The first parameter is observed via standard $watch operation and is examined on every call to $digest() to see if any items have been added, removed, or moved. Our first parameter in this example is a function that takes our target object and creates an array of the keys to watch for changes.

The second parameter is a function that receives the old and new values, and is called whenever the first parameter changes. In this example, we’re just logging the values.

Full directive definition

 1 (function() {
 2     'use strict';
 3 
 4     angular
 5         .module('app.modules.dashboards')
 6         .directive('myController', myController);
 7 
 8     /* @ngInject */
 9     function myController() {
10         var directive = {
11             bindToController: true,
12             controller: Controller,
13             controllerAs: 'myController',
14             restrict: 'A'
15         };
16         return directive;
17     }
18 
19     /* @ngInject */
20     function Controller ($scope, $rootScope, $translate, $timeout) {
21         var vm = this;
22         vm.users = {};
23 	
24 	//watch collection to note differences in old and new users
25 	$scope.$watchCollection(function () {
26 	    return Object.keys(vm.users);
27 	},function(newValue, oldValue){
28 	    //perform any actions necessary on old and new values here
29 	    console.log(oldValue);
30 	    console.log(newValue);
31 	});
32 
33 	/* other logic... */
34 
35     }
36 })();