yearofmoo / AngularJS-Scope.SafeApply

AngularJS $scope.$apply() without the hassle and errors :)
70 stars 23 forks source link

$scope.$safeApply does not exist within directives #2

Open roypeled opened 11 years ago

roypeled commented 11 years ago

It is usable only by accessing $root, like so: $scope.$root.$safeApply()

kentcdodds commented 10 years ago

I believe this is because the isolate scope of scoped directives doesn't inherit from $rootScope. I'm actually interested in how this could be avoided because I just finished writing a Scope.$watchOnce module which adds $watchOnce to the $rootScope and I want to be able to use it on isolate scopes.

Right now, this is what I'm doing:

angular.bind($scope, $scope.$root.$watchOnce)('expression', watcherHandler);

But I'd much rather just more simply do:

$scope.$watchOnce('expression', watchHandler);

Any idea how this could be accomplished in an isolate scope context @matsko?

gion commented 10 years ago

You could add it as a service too and inject it as a dependency in the directive. Take a look at how others did it: https://github.com/cotag/angular-safeapply/blob/master/safe-apply.js

kentcdodds commented 10 years ago

Decided to hijack $new like this. Works great...

var scopePrototype = Object.getPrototypeOf($rootScope);
var oldNew = scopePrototype.$new;
// hijack the prototype's $new
scopePrototype.$new = function $new() {
  var scope = oldNew.apply(this, arguments);
  addFunctionality(scope);
  return scope;
};
roypeled commented 10 years ago

Awesome! Thanks for the fix!

kentcdodds commented 10 years ago

Sorry @roypeled, I didn't fix @matsko's project, I'm talking about how I implemented a fix to the same issue on my project. I'm sure @matsko would love a PR if you want to implement the same fix in this repo...

roypeled commented 10 years ago

Ah okay. I'll see if I have time, but good fix nonetheless.