Chapter 7: Optimizing using $watchCollection

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        <pre>{{ myObj | json }}</pre>
        <pre>{{ myArr | json }}</pre>
        <div><button ng-click="reset()">Reset</button></div>
        <hr />
        <div><button ng-click="myArr = []">myArr = []</button></div>
        <div><button ng-click="myObj = 1">myObj = 1</button></div>
        <div><button ng-click="myObj = {}">myObj = {}</button></div>
        <div><button ng-click="myObj.myPrim = 'Go Giants!'">myObj.myPrim = 'Go Giants!'</button></div>
        <div><button ng-click="myObj.newProp = {}">myObj.newProp = {}</button></div>
        <div><button ng-click="myArr.push(2)">myArr.push(2)</button></div>
        <div><button ng-click="myArr[0] = 6">myArr[0] = 6</button></div>
        <div><button ng-click="del()">delete myObj.myPrim</button></div>
        <div><button ng-click="myObj.innerObj.innerProp = 'Go Blackhawks!'">myObj.innerObj.innerProp = 'Go Blackhawks!'</button></div>
        <div><button ng-click="myObj.innerObj.otherProp = 'Go Sox!'">myObj.innerObj.otherProp = 'Go Sox!'</button></div>
        <div><button ng-click="delInner()">delete myObj.innerObj.innerProp</button></div>
    </div>
</div>

JavaScript

angular.module('myApp', [])
.controller('Ctrl', function ($scope, $log) {
    $scope.reset = function() {
        $scope.myObj = {
            myPrim: 'Go Bears!',
            innerObj: {
                innerProp: 'Go Bulls!'
            }
        };
        $scope.myArr = [3,1,4,1,5,9];
    };
    
    $scope.del = function() {
        delete $scope.myObj.myPrim;
    };
    
    $scope.delInner = function() {
        delete $scope.myObj.innerObj.innerProp;
    };
    
    $scope.reset();
    
    $scope.$watchCollection('myObj', function(newVal, oldVal, scope) {
        // callback logic
        $log.log('myObj watch callback');
    }, true);
    
    $scope.$watchCollection('myArr', function(newVal, oldVal, scope) {
        // callback logic
        $log.log('myArr watch callback');
    }, true);
});