Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

angularjs - Why doesn't a directive with an isolate scope apply the scope to it's DOM element?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your initial markup the active scope is always going to be the parent scope.

It wouldn't make sense to be the directive's scope, because you could have multiple directives. For example:

<custom-directive isolate-value="Hello!" ng-show="true">
    <p>inner element's scope: {{$id}}</p>
    <p>isolate value: {{isolateValue || 'undefined'}}</p>
</custom-directive>

Obviously the scope can't belong to both customDirective and ngShow.

So as you said, the only way to get what you want is to transclude or to use a directive template.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...