I'm trying to work more with directives to apply a bit more best practices but I have some questions on the best way to apply a scope value from a directive.
In this fiddle demo, you can see if you click on the "Toggle displayMenu " button, the div is still toggled on. If you toggle lines 7-8 in directive's code :
scope.yolo = function () {
scope.ctrl.toggle(); // COMMENT ME
//scope.ctrl.toggleApply(); // UNCOMMENT ME
};
to :
scope.yolo = function () {
//scope.ctrl.toggle(); // COMMENT ME
scope.ctrl.toggleApply(); // UNCOMMENT ME
};
the displayMenu div will toggle off.
Now, the problem is I am forced to write 2 functions, one with "$scope.$apply" and one without, and it is clearly not a smart way to do it... unless I use safeApply like :
$rootScope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
Is the safeApply is the best practice ? If not, what is the best way to accomplish what I want ?