Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if scope is isolated?

Is somehow possible to check whether angular scope is isolated or not, having the scope only?

I know, that isolated and not isolated scopes have different prototypes. However these prototypes are private in angular and cannot be easily accessed. Checking the prototype name seems quite dirty approach.

Any better idea?

like image 611
Kędrzu Avatar asked Apr 29 '16 14:04

Kędrzu


3 Answers

The first difference I know is, that Isolated scope has "$root" field, which is rootScope.

The second difference is, that Isolated scope has "$$isolateBindings" field, but not isolated has not

like image 128
Hazarapet Tunanyan Avatar answered Oct 06 '22 06:10

Hazarapet Tunanyan


Per the documentation, the following should do the trick:

$element.isolateScope()

retrieves an isolate scope if one is attached directly to the current element. This getter should be used only on elements that contain a directive which starts a new isolate scope. Calling scope() on this element always returns the original non-isolate scope. Requires Debug Data to be enabled.

https://docs.angularjs.org/api/ng/function/angular.element#jquery-jqlite-extras

As mentioned in the docs, if you configure the following (as you should in production):

$compileProvider.debugInfoEnabled(false);

This method will no longer work... I suppose the primary reason to obtain the isolateScope this way is for unit tests and there isn't really a reason to conditionally perform some action on scope isolation (correct me if I'm wrong).

https://jsfiddle.net/r0m4n/f84yzdt4/

like image 41
r0m4n Avatar answered Oct 06 '22 07:10

r0m4n


You can check it like this:

if (scope.hasOwnProperty('$root') && scope.$root !== scope && scope.$root) {
    // the scope is isolate
}

It isn't perfect as it relies on implementation details, but I can't think of anything better than this.

Explanation:

  1. scope.hasOwnProperty('$root'). Every scope has this property. It points to the closest ancestor scope that is isolate or $rootScope. This property is inherited prototypically, so it's own only for isolate scopes and $rootScope.

  2. scope.$root !== scope. Checking that the scope isn't $rootScope.

  3. scope.$root. Can be replaced with !scope.$$destroyed. When a scope is destroyed, null is assigned to many of its properties including $root, so the property becomes own.

like image 25
thorn0 Avatar answered Oct 06 '22 06:10

thorn0