Chapter 4: Safe $apply

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        <button ng-click="increment()">Increment</button>
        {{ val }}
    </div>
</div>

JavaScript

angular.module('myApp', [])
.controller('Ctrl', function ($scope, $timeout) {
    $scope.val = 0;
    
    // method that may or may not be called from somewhere
    // that will not trigger a $digest
    $scope.increment = function () {
        // wraps model modification in $timeout promise
        $timeout(function() {
            $scope.val++;
        });
    };
    
    // application component that modifies the model without
    // triggering a $digest
    /*setInterval(function () {
        $scope.increment();
    }, 1000);*/
});