我在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行为的一些事情吗?或者这是一个错误?
答案 0 :(得分:4)
看起来用斜杠关闭开始标记内的标记会导致问题。添加明确的结束标记将解决问题。
在您的指令示例中:<test />
应为<test></test>
在您的ng-include示例中:<ng-include src="'test.html'" />
应为<ng-include src="'test.html'"></ng-include>
请参阅此simplified fiddle,在没有ng-repeat的情况下重现问题,并使用结束标记this fixed fiddle。