Joined November 2013
·

Nathan Walker

Portland, OR
·
·

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

Doing this with a service (as suggested above @andrewreutter) comes far too late for some use cases. Be a cool cat on the block, and use a decorator to configure this VERY early in your applications bootstrap phase before any module's services, directives, etc may try to access it before its available :)

yourAwesomeModule.config([
  '$provide', function($provide) {
    return $provide.decorator('$rootScope', [
      '$delegate', function($delegate) {
        $delegate.safeApply = function(fn) {
          var phase = $delegate.$$phase;
          if (phase === "$apply" || phase === "$digest") {
            if (fn && typeof fn === 'function') {
              fn();
            }
          } else {
            $delegate.$apply(fn);
          }
        };
        return $delegate;
      }
    ]);
  }
]);
Achievements
31 Karma
0 Total ProTip Views