Created
August 25, 2013 16:58
-
-
Save PatrickJS/6334981 to your computer and use it in GitHub Desktop.
If you find yourself triggering the '$apply already in progress' error while developing with Angular.JS (for me I find I hit most often when integrating third party plugins that trigger a lot of DOM events), you can use a 'safeApply' method that checks the current phase before executing your function. I usually just monkey patch this into the $s…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| .factory('safeApply', ['$rootScope', function($rootScope) { | |
| return function($scope, fn) { | |
| var phase = $scope.$root.$$phase; | |
| if(phase == '$apply' || phase == '$digest') { | |
| if (fn) { | |
| $scope.$eval(fn); | |
| } | |
| } else { | |
| if (fn) { | |
| $scope.$apply(fn); | |
| } else { | |
| $scope.$apply(); | |
| } | |
| } | |
| } | |
| }]) | |
| .controller('MyCtrl', ['$scope,' 'safeApply', function($scope, safeApply) { | |
| safeApply($scope); // no function passed in | |
| safeApply($scope, function() { // passing a function in | |
| }); | |
| }]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment