angularjsHow do I use the scope.apply() method in AngularJS?
The scope.apply()
method is used in AngularJS to execute an expression in the context of the current scope. This allows the model and view to be kept in sync, and it is especially useful when working with asynchronous events.
For example, if a user clicks a button, the following code can be used to update the model:
$scope.clickButton = function() {
$scope.value = 'clicked';
$scope.$apply();
};
The $scope.$apply()
call will cause the model to be updated, and the view will be updated accordingly.
The scope.apply()
method is also useful for wrapping external callbacks in AngularJS context. For example, the following code will execute the onChange
callback within the current scope:
$scope.onChange = function(value) {
$scope.value = value;
};
externalService.registerCallback($scope.$apply.bind($scope, $scope.onChange));
Code explanation
$scope.clickButton = function() { ... }
- this function is called when the user clicks a button and updates the model$scope.$apply()
- this call updates the model and causes the view to be updated$scope.onChange = function(value) { ... }
- this function is called when the external service reports a change in the valueexternalService.registerCallback($scope.$apply.bind($scope, $scope.onChange))
- this call wraps theonChange
callback in the current scope
Helpful links
More of Angularjs
- How do I use Angular to zip files?
- How can I use Zone.js with Angular to detect and act upon asynchronous events?
- How can I use AngularJS to create a zone in my software development project?
- How do I use Angular Zone to detect and run Angular change detection?
- How do I use Angular with YAML?
- How can I create an editable AngularJS application?
- How do I implement one-way binding in AngularJS?
- How can I become an Angular expert from a beginner level?
- How can I use an AngularJS XSS cheat sheet to protect my website from malicious attacks?
- How can I use Angular to zoom in and out of a div?
See more codes...