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?
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
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/
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:
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
.
scope.$root !== scope
. Checking that the scope isn't $rootScope
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With