【问题标题】:Angular nested directive only the first child is rendered [duplicate]Angular嵌套指令仅呈现第一个孩子[重复]
【发布时间】:2016-07-05 13:45:40
【问题描述】:

我有一个parent 指令,其中包括两个子指令firstsecond。我注意到只有第一个孩子被渲染。另外,如果我在第一个之前放置了一些任意的 HTML 标记,它就会全部呈现,但如果我把它们放在之后,它们就不会显示出来。这是为什么呢?

jsfiddle

<!-- index.html -->
<div ng-app="myApp">
  <my-parent-dir />
</div>

<!-- main.js -->
var app = angular.module("myApp", []);
app.directive("myParentDir", function() {
    return {
        restrict: 'E',
        template: '<my-first-child /> <my-second-child />'
    };
});

app.directive("myFirstChild", function() {
    return {
        restrict: 'E',
        template: '<input type="text" placeholder="first">',
    };
});

app.directive("mySecondChild", function() {
    return {
        restrict: 'E',
        template: '<input type="text" placeholder="second">',
    };
});

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    尝试像这样使用它:

    var app = angular.module("myApp", []);
    app.directive("myParentDir", function() {
        return {
            restrict: 'E',
            template: '<my-first-child></my-first-child> <my-second-child></my-second-child>'
        };
    });
    

    来自角度issues in github

    html 规范定义的自闭合或 void 元素非常 浏览器解析器特有的。你不能自己做,所以为了你的 自定义元素你必须坚持非空元素()。

    这不能改变角度。

    【讨论】:

      【解决方案2】:

      由于您使用的是自定义标签,因此您需要关闭标签,因为 HTML 规范 不允许自关闭标签。

      template: '<my-first-child></my-first-child> <my-second-child></my-second-child>'
      

      JSFiddle

      【讨论】:

        【解决方案3】:

        自定义标签不是叶子标签,所以你必须使用:

        template:'<my-first-child></my-first-child> <my-second-child></my-second-child>'
        

        【讨论】:

        • 谢谢。比我想象的要容易。
        • 这是更新后的fiddle
        猜你喜欢
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 2016-07-08
        • 2012-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        相关资源
        最近更新 更多