【问题标题】:Why does ngRepeat not include elements after ngInclude or directive?为什么 ngRepeat 不包含 ngInclude 或指令之后的元素?
【发布时间】:2014-01-31 16:27:13
【问题描述】:

我遇到了来自 ngRepeat 指令的一些意外行为。这是一个非常简单的例子:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="app">
<body ng-controller="ctrl">

    <h1>test with directive</h1>
    <ul>
        <li ng-repeat="item in list">           
            <div>
                <test />
                <p>And another thing...</p>
            </div>
        </li>
    </ul>

    <h1>test with ng-include</h1>
    <ul>
        <li ng-repeat="item in list">
            <ng-include src="'test.html'" />
            <p>And another thing...</p>
        </li>
    </ul>

    <h1>test with inline switch</h1>
    <ul>
        <li ng-repeat="item in list">
            Hello, 
            <div ng-switch="item.name">
                <div ng-switch-when="John">Johnny-boy</div>
                <div ng-switch-when="Mary">Mary-doll</div>
            </div>
            !
            <p>And another thing...</p>
        </li>
    </ul>   

    <script src="angular.js" type="text/javascript"></script>
    <script type="text/javascript">

        var app = angular.module("app", []);

        app.directive("test", function () {
            return {
                restrict: "E",
                scope: false,
                templateUrl: function () { return "test.html" },
                replace: true,
                link: function (scope, elem, attrs) {
                    console.log(scope, elem, attrs);
                }
            }
        });

        app.controller("ctrl", function ($scope) {
            $scope.list = [ { name: "John" }, { name: "Mary" } ];
        });

    </script>   
</body>
</html>

test.html 文件如下所示:

<div>
    Hello, 
    <div ng-switch="item.name">
        <div ng-switch-when="John">Johnny-boy</div>
        <div ng-switch-when="Mary">Mary-doll</div>
    </div>
    !
    <hr/>
</div>

我希望每个测试的输出都相同(使用指令、ng-include 或内联 html)。然而,对于指令和 ng-include 测试,ng-repeat 中的最后一个 p 元素丢失了。也就是说,这一行……​​

<p>And another thing...</p>

.. 不会进入 DOM。我是否遗漏了有关 ng-repeat 行为的一些信息?还是bug?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    看起来用斜杠关闭开始标签内的标签会导致问题。添加显式结束标记将解决此问题。

    在您的指令示例中:&lt;test /&gt; 应该是 &lt;test&gt;&lt;/test&gt;

    在您的 ng-include 示例中:&lt;ng-include src="'test.html'" /&gt; 应该是 &lt;ng-include src="'test.html'"&gt;&lt;/ng-include&gt;


    请参阅此simplified fiddle 重现该问题而不使用 ng-repeat 和 this fixed fiddle 带有结束标签。

    【讨论】:

    • 谢谢!使用显式结束标签,一切似乎都符合预期。不敢相信我没想过要尝试。
    • @Gloopy 感谢您指出这一点,rom99 为什么不将其标记为正确答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2011-01-11
    • 2013-03-30
    • 1970-01-01
    • 2019-01-19
    • 2013-01-10
    相关资源
    最近更新 更多