为什么带有隔离范围的指令不将该范围应用于其DOM元素? [英] Why doesn't a directive with an isolate scope apply the scope to it's DOM element?

查看:181
本文介绍了为什么带有隔离范围的指令不将该范围应用于其DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚AngularJS范围是如何工作的.我也很好奇为什么他们会按照自己的方式工作.我认为以下行为没有任何意义(提琴1 ).

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

DOM元素及其内容保留在父作用域(id = 1)中,因此阻止了视图访问正确的作用域(id = 2).将HTML代码移动到模板中可使它按预期方式工作(小提琴2 ),但它与我的初始代码冲突将指令用作可重用组件(即相同的数据,不同的视图)的观点.

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).

我使它可以包含在内(小提琴3 ),但是由于需要,它感觉有些笨拙用$ parent属性引用正确的作用域(包含会创建另一个作用域).

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).

那么,此指令与DOM隔离作用域不匹配之间有一些隐藏的含义吗?还是可以以某种方式将DOM范围调整为隔离范围?

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?

推荐答案

使用terminal:true,然后$自己编译.

Use terminal: true, and $compile yourself.

http://jsfiddle.net/SE_YOU/rrzrtL4e/

function Directive($compile) {
    return {
        restrict: 'EA',
        terminal: true,
        scope: { isolateValue: "@" },
        link: function(scope, element, attr) {
            console.log("isolate scope: " + scope.$id);
            console.log("isolate value: " + scope.isolateValue);
            $compile(element.contents())(scope);
        }
    };
}

angular
    .module('app',[])
    .directive('customDirective', Directive);

这篇关于为什么带有隔离范围的指令不将该范围应用于其DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆