rom99
rom99

Reputation: 799

Why does ngRepeat not include elements after ngInclude or directive?

I'm experiencing some unexpected behaviour from ngRepeat directive. Here's a really simple example:

<!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>

The test.html file looks like this:

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

I'd expect the same output from each test (using directive, ng-include or inline html). However for the directive and ng-include tests the final p element in the ng-repeat is missing. In other words, this line...

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

..doesn't make it into the DOM. Am I missing something about the behaviour of ng-repeat? Or is it a bug?

Upvotes: 3

Views: 489

Answers (1)

Gloopy
Gloopy

Reputation: 37785

It looks like closing the tags inside the start tag with a slash is causing the problem. Adding an explicit closing tag will fix the issue.

In your directive example: <test /> should be <test></test>

In your ng-include example: <ng-include src="'test.html'" /> should be <ng-include src="'test.html'"></ng-include>


See this simplified fiddle reproducing the issue without an ng-repeat and this fixed fiddle with the closing tags.

Upvotes: 4

Related Questions