Updating DOM after $scope Change

Shows how to get out of the current digest cycle to update the DOM after mutating the model in Angular.

by Jeremy Likness

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
    <button ng-click="add()" data-ng-if="fruits.length === 3">Add</button>
    <div id="fruits">
        <button ng-repeat="fruit in fruits" onclick="alert(this.innerHTML + ' clicked');">{{fruit}}</button>
    </div>
</div>

JavaScript

(function() {
    var app = angular.module("myApp", []);
    app.controller("myController", function($scope) {
        $scope.fruits = ["orange", "plum", "cherry"];
        $scope.add = function() {
            $scope.fruits.push("apple");
            setTimeout(function() {
                $('#fruits').children().eq(-1).click();
            }, 0);
        }
    });
})();