【问题标题】:why does having a <p/> tag within a directive's transcluded content change the scope hierarchy?为什么在指令的嵌入内容中有一个 <p/> 标签会改变范围层次结构?
【发布时间】:2014-10-24 15:29:54
【问题描述】:

最好用几个小提琴来解释。我在两者中都使用了这些简单的指令:

var demo = angular.module('demo', []);

demo.directive('redBox', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div class="bg-red size-med"><b>I am inside a red box.</b><div ng-transclude></div></div>'
    }
});

demo.directive('blueBox', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div class="bg-blue size-med"><b>I am inside a blue box.</b><div ng-transclude></div></div>'
    }
});

function MyCtrl ($scope) {  

};

我将这两个都包括在内,并在Fiddle #1 中打印范围ID。这如我所料 - redBox 和 blueBox 的范围都是 MyCtrl 范围的子级。

<div ng-app='demo'>
    <div ng-controller='MyCtrl'>
        My scope's id is {{$id}}.  <br/>  My parent scope's id is {{ $parent.$id }}. 

        <red-box>
            My scope's id is {{$id}}.  <br/>  My parent scope's id is {{ $parent.$id }}.
        </red-box>

        <blue-box>
            My scope's id is {{$id}}.  <br/>   My parent scope's id is {{ $parent.$id }}.
        </blue-box>
    </div>

</div>

Fiddle #2 中,我只是在其中一个div 的内容中添加了一个标签。这改变了范围层次结构!即使它们没有嵌套,一个指令的范围也是另一个指令的父级。

这里发生了什么?这如何改变范围的父子关系?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    在 Html5 中&lt;p /&gt; 表示&lt;p&gt;,因为&lt;p&gt; 不是“自闭合标签”。

    所以,这个:

    <p/>My parent scope's id is {{ $parent.$id }}.
    

    您的浏览器会这样解释:

    <p>My parent scope's id is {{ $parent.$id }}.</p>
    

    你可能想看看at this question

    【讨论】:

    • 感谢@Josep,对(相对)初学者非常有用。另外,我不妨指出,我最讨厌的一个问题是,当人们对那些显然只是想学习的人提出的问题提出尖刻的问题时。还有当他们不知道如何拼写“pet peeve”时。
    猜你喜欢
    • 2014-05-31
    • 2019-07-29
    • 1970-01-01
    • 2016-10-25
    • 2016-03-06
    • 1970-01-01
    • 2015-09-18
    • 2016-12-22
    相关资源
    最近更新 更多