Angular Function binding

by mslocum

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.js"></script>
<div ng-controller='test'>
  <h2>To Test</h2>
  <ol>
    <li>Setup either a Scope or Function Watch</li>
    <li>Click Test Digest (maybe a couple times)</li>
    <li>Click Clear Watches</li>
    <li>Go back to #1 and do the other type of watch</li>
  </ol>
  <input type="number" ng-model="amt"/>
  <button ng-click="setupScopeWatch()">
    Setup Scope Watch
  </button>
  <button ng-click="setupFuncWatch()">
    Setup Function Watch
  </button>
  <button ng-click="clearWatches()">
    Clear Watches
  </button>
  <br/>
  <button ng-click="testDigest()">
    Test Digest
  </button>
</div>

JavaScript

var app = angular.module('myApp', []);

app.controller('test', function($scope) {

	$scope.amt = 100000;
  var aWatches = [];

	$scope.setupScopeWatch = function() {
  	var i = $scope.amt;
    while (--i) {
    	aWatches.push($scope.$watch('amt', function() {}));
    }
  };
  
	$scope.setupFuncWatch = function() {
  	var i = $scope.amt;
    while (--i) {
    	aWatches.push($scope.$watch(function() { return $scope.amt; }, function() {}));
    }
  };
  
  $scope.clearWatches = function() {
  	aWatches.forEach(function(f) {
    	f();
    })
    aWatches = [];
  };
  
	$scope.testDigest = function() {
  	setTimeout(function() {
    	var startTime = performance.now();
      $scope.$digest();
      var duration = performance.now() - startTime;
      alert("Digest Duration (ms): " + duration);
    }, 0);
  }
});