[AngularJS] Safe Scope.$apply Implementation (Error: $apply already in progress)
source link: http://siongui.github.io/2013/04/04/angularjs-safe-scope-apply/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[AngularJS] Safe Scope.$apply Implementation (Error: $apply already in progress)
Updated: February 23, 2015
One of the headaches of writing one's own directives or services of AngularJS application is that get the following error message while the $apply method of scope is called:
Error: $apply already in progress
The following is my solution (call the following safeApply method instead of $apply):
$scope.safeApply = function(fn) { var phase = this.$root.$$phase; if(phase == '$apply' || phase == '$digest') this.$eval(fn); else this.$apply(fn); }; // OR function safeApply(scope, fn) { var phase = scope.$root.$$phase; if(phase == '$apply' || phase == '$digest') scope.$eval(fn); else scope.$apply(fn); }
The fn in above sample code could be AngularJS expression or JavaScript function, depending on your need.
References:
[1]my gist
[2]angularjs - Prevent error $digest already in progress when calling $scope.$apply() - Stack Overflow
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK