AngularJS - How to find when items are added or removed from collection

AngularJS provides a lot of features that some time we don't pay attention to or overlook. Other day somebody asked me a question about watching collection when new items are added or existing items are removed. Lot of developers tend to focus on using $watch method on scope to keep track of when changes happen to certain properties or objects in a scope. If you read the documentation for $watch, you will notice that it says that equality is compared by reference. What does this mean for collections? This means that once your object for a collection has been created, $watch will never be able to notify you when objects are added or removed because collection object itself has not changed. Only the inside content has changed. Unless you destroy the previous collection object itself and recreate it, $watch is not the method that you will be using.

$watchCollection

$watchCollection is the method you will be using if you want to keep track of when items are added or removed from your collection object in angular scope. Syntax for $watch and $watchCollection is the same. $watchCollection will provide you access to new and old collection items. This will allow you to check what change has happened to items in the collection.

Here is an example of how I used it in one of my directives. The directive monitors are latency values are added to the collection. Based on that it processes the new values to create a line chart using D3.js.


 PortalApp.directive('latencyChart', [
 function() {
     var directiveObj = {
         restrict: 'E',
         scope: {
             latencies: '=',
             chartType:'@'
         },
         transclude: true,
         template:"<div id='latChart'><svg></svg></div>",
         link: function (scope, element, attr, ctrl) {
             var chartObj = null;
             var trimmedData = [];
    scope.$watchCollection('latencies', function (newVal, oldVal) {
                 trimmedData = newVal.slice(0, 10).reverse();
                 redraw();
             });
             var redraw = function() {
                 
             }
         }
     };
     return directiveObj;
 }
]);

Search

Social

Weather

-3.5 °C / 25.6 °F

weather conditions Clouds

Monthly Posts

Blog Tags