我对AngularJS 1.6.0(与旧版本相同)和ngRepeat指令有一个奇怪的问题,当用作嵌套在表格中的元素时。
只需将<ng-repeat>
放入<table>
,然后将<tr>
放入其中:它不起作用。
但是如果你将<ng-repeat>
放在<table>
之外,例如。内置<div>
,效果很好。
在检查我们的错误情况下呈现的HTML时,我们可以看到ng-repeat的迭代,但是它们会离开表格,从而破坏DOM并使线条消失:
<p>When placed inside a table, with tr inside, it doesn't work:</p>
<!-- ngRepeat: person in people --><ng-repeat ng-repeat="person in people" class="ng-scope">
</ng-repeat><!-- end ngRepeat: person in people --><ng-repeat ng-repeat="person in people" class="ng-scope">
</ng-repeat><!-- end ngRepeat: person in people --><ng-repeat ng-repeat="person in people" class="ng-scope">
</ng-repeat><!-- end ngRepeat: person in people -->
<table>
<tbody>
<tr>
<td class="ng-binding"></td>
</tr>
</tbody>
</table>
使用最新的Chrome和Firefox进行测试。
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.people = [{
name: 'John',
age: 20
}, {
name: 'Peter',
age: 22
}, {
name: 'Jane',
age: 19
}];
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<meta charset=utf-8 />
<title>ngRepeat</title>
</head>
<body>
<div ng-controller="MyCtrl">
<p>Hello ng-repeat!</p>
<p>With div inside, ng-repeat element works:</p>
<ng-repeat ng-repeat="person in people">
<div>
<td>{{person.name}}</td>
</div>
</ng-repeat>
<p>When ng-repeat element is placed inside a table, with tr inside, <strong>it doesn't work</strong>:</p>
<table>
<ng-repeat ng-repeat="person in people">
<tr>
<td>{{person.name}}</td>
</tr>
</ng-repeat>
</table>
<p>But, when ng-repeat is used as an attribute on tr, it works!</p>
<table>
<tr ng-repeat="person in people">
<td>{{person.name}}</td>
</tr>
</table>
</div>
</body>
</html>
我错过了什么吗?
答案 0 :(得分:3)
ng-repeat
不是table
标记中的有效元素,浏览器不会抱怨无法识别的属性。
tr
,tbody
,thead
是表格标记中的有效元素。
这里我只是将表中的ng-repeat
更改为tbody。那么它就可以了。
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.people = [{
name: 'John',
age: 20
}, {
name: 'Peter',
age: 22
}, {
name: 'Jane',
age: 19
}];
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<meta charset=utf-8 />
<title>ngRepeat</title>
</head>
<body>
<div ng-controller="MyCtrl">
<p>Hello ng-repeat!</p>
<p>With div inside, ng-repeat element works:</p>
<ng-repeat ng-repeat="person in people">
<div>
<td>{{person.name}}</td>
</div>
</ng-repeat>
<p>When ng-repeat element is placed inside a table, with tr inside, <strong>it doesn't work</strong>:</p>
<table>
<tbody ng-repeat="person in people">
<tr>
<td>{{person.name}}</td>
</tr>
</tbody>
</table>
<p>But, when ng-repeat is used as an attribute on tr, it works!</p>
<table>
<tr ng-repeat="person in people">
<td>{{person.name}}</td>
</tr>
</table>
</div>
</body>
</html>