Chapter 10: Preventing redundant parsing

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="OuterCtrl">
    <div ng-repeat="player in data.playerIds" 
         ng-controller="InnerCtrl">
    </div>
  </div>
</div>

JavaScript

angular.module('myApp', [])
.controller('OuterCtrl', function($scope, $log, $parse) {
    $scope.data = {
        playerIds: [1,2,3],
        // perform the $parse once and expose the returned
        // function on $scope
        repeatParsed: $parse(
            (function() {
                $log.log("Parse compilation called");
                return 'myExp()';
            })()
        )
    };
})
.controller('InnerCtrl', function($scope, $log) {
    $scope.myExp = function() {
        $log.log("Expression evaluated");
        return 'watchedValue';
    };
    // each watcher will implicitly invoke the $parse() return
    // function with $scope as the parameter
    $scope.$watch($scope.data.repeatParsed, function(newVal) {
        $log.log("Watch handler called: ", newVal);
        alert(newVal);
    });
});