Angular.js $watchCollection
September 15, 2015
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)
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.