I'm trying to figure out how AngularJS scopes work. I'm also curious why they work the way they do. I think the following behavior doesn't make sense (fiddle 1).
<div ng-app="app">
<p>outer element's scope: {{$id}}</p>
<custom-directive isolate-value="Hello!">
<p>inner element's scope: {{$id}}</p>
<p>isolate value: {{isolateValue || 'undefined'}}</p>
</custom-directive>
</div>
function Directive() {
return {
restrict: 'E',
scope: { isolateValue: "@" },
link: function(scope, element, attributes) {
console.log("isolate scope: " + scope.$id);
console.log("isolate value: " + scope.isolateValue);
}
};
}
angular
.module('app',[])
.directive('customDirective', Directive);
I'm expecting the view to print "isolate value: Hello!" but I get "undefined" instead:
outer element's scope: 1
inner element's scope: 1
isolate value: undefined
The DOM element and its contents remain in the parent scope (id = 1) thus preventing the view from accessing the correct scope (id = 2). Moving the HTML code into a template makes it work as expected (fiddle 2) but it conflicts with my initial point of using the directive as a reusable component (i.e. same data, different views).
I made it work with transclusion (fiddle 3) but it feels somewhat hacky because of the need to refer to the correct scope with $parent property (transclusion creates one more scope).
So, it there some hidden meaning behind this directive vs. DOM isolate scope mismatch thing? Or maybe DOM scope can be somehow tuned to the isolate one?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…