我编辑了这个问题,因为它变得太长了 嗨,我有这个角度代码:
var mod = angular
.module("myMod",[])
.controller("myCont",function($scope){
var obj = [
{name : "Monica", others :[{age:20},{salary:20000}]},
{name : "Rachel", others :[{age:16},{salary:28000}]},
{name : "Pheobe", others :[{age:24},{salary:30000}]}
]
$scope.obj1 = obj;
})
和这个html文件:
<!DOCTYPE HTML>
<html >
<head>
<script src = "angular.js"></script>
<script src = "angularmy.js"></script>
</head>
<body ng-app="myMod" ng-controller="myCont">
<div>
<ol>
<li ng-repeat="item in obj1" ng-init="parentIndex=$index">{{item.name}}
<ol ng-repeat="items in item.others">
<li >{{items.age }} parentIndex - {{parentIndex}} index - {{$index}}</li>
<li >{{items.salary }} parentIndex - {{parentIndex}} index - {{$index}}</li>
</ol>
</li>
</ol>
</div>
</body>
</html>
但是它给第二个嵌套列表项的索引也是0:
莫妮卡
拉结
Pheobe
有人可以告诉我这段代码有什么问题吗?为什么要输出四个输出而不是2 ???
答案 0 :(得分:0)
试试这个:
<ol ng-repeat="items in item.others track by $index">
<li>{{items.age}} parentIndex - {{parentIndex}} index - {{$index}}</li>
<li>{{items.salary}} parentIndex - {{parentIndex}} index - {{$index}}</li>
</ol>
答案 1 :(得分:0)
根据this你想要完成的是:
<li ng-repeat="item in obj1">{{item.name}}
<ol ng-repeat="o in item.others">
<li>{{o.age}} parentIndex - {{$parent.$index}} index - {{$index}}</li>
<li>{{o.salary}} parentIndex - {{$parent.$index}} index - {{$index}}</li>
</ol>
</li>
答案 2 :(得分:0)
为了帮助您可视化显示的内容,您应该考虑在ng-repeats中使用更有用的变量名称,尤其是在它们开始嵌套时。
控制器:
var mod = angular
.module("myMod",[])
.controller("myCont",function($scope){
var obj = [
{name : "Monica", others :[{age:26,salary:20000}]},
{name : "Rachel", others :[{age:28,salary:28000}]},
{name : "Pheobe", others :[{age:29,salary:30000}]}
]
$scope.obj1 = obj;
})
模板:
(此处我已将ol
替换为ul
,以避免另一个潜在的混淆来源)
<body ng-app="myMod" ng-controller="myCont">
<ul>
<li ng-repeat="person in obj1" >Name: {{person.name}} | Person Index: {{$index}}
<ul ng-repeat="detail in person.others">
<li>Age: {{detail.age}} | Salary: {{detail.salary}} | Index: {{$index}} | Parent Index: {{$parent.$index}}</li>
</ul>
</li>
</ul>
</body>
你最大的问题是你的第二次重复训练中有2 x li
s。
输出:
Name: Monica | Person Index: 0
Age: 26 | Salary: 20000 | Index: 0 | Parent Index: 0
Name: Rachel | Person Index: 1
Age: 28 | Salary: 28000 | Index: 0 | Parent Index: 1
Name: Pheobe | Person Index: 2
Age: 29 | Salary: 30000 | Index: 0 | Parent Index: 2