// a cleaner safeApply
// decorate the root scope
angular.module('myApp', [])
.config(function($provide) {
// define decorator for $rootScope service
return $provide.decorator('$rootScope', function($delegate) {
// $delegate acts as the $rootScope instance
$delegate.safeApply = function(func) {
var currentPhase = $delegate.$$phase;
// determine if already in $apply/$digest phase
if (currentPhase === "$apply" ||
currentPhase === "$digest") {
// already inside $apply/$digest phase
// if safeApply() was passed a function, invoke it
if (typeof func === 'function') {
func();
}
}
else {
// not inside $apply/$digest phase, safe to invoke $apply
$delegate.$apply(func);
}
};
return $delegate;
});
})
.controller('Ctrl', function ($scope) {
$scope.val = 0;
// method that may or may not be called from somewhere
// that will not trigger a $digest
$scope.increment = function () {
$scope.val++;
$scope.safeApply();
};
// application component that modifies the model without
// triggering a $digest
setInterval(function () {
$scope.increment();
}, 1000);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.