The AngularJS $apply
function is used to execute an expression in AngularJS from outside of the angular framework. When the $apply()
function call finishes AngularJS calls $digest()
internally, so all data bindings are updated. That make sure that all watches are checked, and thus all data bindings refreshed. The $apply
function takes a function as parameter to execute.
Syntax
$apply([exp]);
<!DOCTYPE html>
<html>
<head> <!-- www.techstrikers.com -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS $apply Example</title>
<script>
var app = angular.module('app', []);
app.controller("ApplyController", function($scope) {
$scope.applyTest = "Default Value";
$scope.updateApplyTest = function() {
$scope.applyTest = "From Inside AngularJS";
}
document.getElementById("updateApplyTestJavascriptWithoutApply")
.addEventListener('click', function() {
$scope.applyTest = "From Outside AngularJS Using $digest()";
$scope.$digest();
});
document.getElementById("updateApplyTestJavascript")
.addEventListener('click', function() {
$scope.$apply(function() {
$scope.applyTest = "From Outside AngularJS Using $apply()";
});
});
});
</script>
</head>
<body style="background-color:#DDE4E9;">
<fieldset style="background-color:#DDE4E9;">
<legend>AngulerJS $apply Method Example</legend>
<div ng-app="app">
<div ng-controller="ApplyController">
<p style="font-family:Arial;color:yellow;background:steelblue;padding:3px;width:350px;"
>{{applyTest}}</p>
<button ng-click="updateApplyTest()">Update Using ng-click</button>
<button id="updateApplyTestJavascriptWithoutApply">
Update Using Javascript click with $digest()</button>
<button id="updateApplyTestJavascript">
Update Using Javascript click with $apply()</button>
</div>
</div>
</fieldset>
</body>
</html>