Reputation: 494
I'm referring an AngularJS study material and tried to implement "Directive with Isolated scope", but it's not working. Please find below given pieces of code, I've done.
HTML:
<body ng-app="myApp">
<div ng-init="myProperty = 'wow, this is cool'">
Surrounding scope: {{ myProperty }}
<div my-inherit-scope-directive>
Inside an directive with inherited scope: {{ myProperty }}
</div>
<div my-directive>
Inside myDirective, isolate scope: {{ myProperty }}
<div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
restrict: 'A',
scope: {}
};
});
app.directive('myInheritScopeDirective', function() {
return {
restrict: 'A',
scope: true
};
});
Angular JS:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
Actual Output:
Surrounding scope: wow, this is cool
Inside an directive with inherited scope: wow, this is cool
Inside myDirective, isolate scope: wow, this is cool
Expected Output:
Surrounding scope: wow, this is cool
Inside an directive with inherited scope: wow, this is cool
Inside myDirective, isolate scope:
Difference lies in last line of outputs.
I agree, several questions with resembling title are already present on SO. I've been through them, believe me, none could answer my query. So, thought about asking question specific to my requirement.
Upvotes: 4
Views: 1355
Reputation: 7911
As per Angular's compile.js
docs comment, (for scope
attribute of a directive)
{...}
(an object hash): A new "isolate" scope is created for the directive's template. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope. Note that an isolate scope directive without atemplate
ortemplateUrl
will not apply the isolate scope to its children elements.
And, here you don't have template
/templateUrl
so it works that way.
Here's your working example with template
Edit: Here's a closed github issue regarding this which explains the why part:
A comment by gkalpak
Indeed it doesn't sound like a good practice to rely on a component-directive's internals from the HTML (i.e. have child DOM elements that assume certain things about a directive on their parent) - if the contents are specific to a component, they belond in it's template.
In that respect, it does sounds reasonable.
Edit 2: This was introduced as part of Angular@1.2.0 timely-delivery (2013-11-08)
hence it works anyway in the versions before that.
As per CHANGELOG: (v1.2.0 Breaking Changes)
$compile:
- due to d0efd5ee, Child elements that are defined either in the application template or in some other directives template do not get the isolate scope. In theory, nobody should rely on this behavior, as it is very rare - in most cases the isolate directive has a template.
Upvotes: 3