Joined May 2013
·

Andrew Reutter

Austin, TX
·
·

Posted to 'Safe' $apply in Angular.JS over 1 year ago

Here's safeApply as an Angular service you can attach to your module. Additionally, this version accounts for calls to $apply() that don't pass in a function. To use it, attach the following to your module:

.factory('safeApply', [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();
            }
        }
    }
}])

and access it with dependency injection:

.controller('MyCtrl', ['$scope,' 'safeApply', function($scope, safeApply) {
    safeApply($scope);                     // no function passed in
    safeApply($scope, function() {   // passing a function in
    });
}])
Achievements
1 Karma
0 Total ProTip Views