我有以下应用程序,我在其中循环一些数据并显示它。
<div class="thing" ng-repeat="thing in things">
<h1>{{thing.title}}</h1>
<p>{{thing.description}}</p>
<br/>
<div class="child">
<!-- ng-repeat="child in ??? -->
<p>Display child here</p>
</div>
</div>
我的数据:
$scope.things = [{
id: 1,
title: 'First thing',
description: 'This is just a thing',
extra: {
childs: 3 /* the id of the children */
}
}, {
id: 2,
title: 'Second thing',
description: 'This is just a thing',
extra: {}
}, { /* dont displat this object in the ng-repeat="thing in things" */
id: 3,
title: 'Child thing',
description: 'This is a child thing',
extra: {}
}]
我不明白的是如何ng-repeat
仅不是 child 的事物并在.child
div中显示id 为 thing.extra.childs
的元素。
有人可以解释一下如何实现这一目标吗?
最佳答案
您肯定需要改变数据对象。您也不希望 child 显示在列表中。基本上迭代并将子对象移动到额外的键中。即解析引用
** 您不希望在显示中处理复杂的逻辑,因此在您的模型中您应该做所有肮脏的工作。由于您无法更改 API,我们将更改 API 引用
在你的 Controller 中,我猜这将来自 API,假设你在变量 data
中有 JSON。
//data will be coming from API
/*data = [{
id: 1,
title: 'First thing',
description: 'This is just a thing',
extra: {
childs: 3
}
}, {
id: 2,
title: 'Second thing',
description: 'This is just a thing',
extra: {}
}, {
id: 3,
title: 'Child thing',
description: 'This is a child thing',
extra: {}
}]; */
然后,您可以在收到数据的下方修改此 JSON,并将此代码放入 Controller 中。
for(var i in data){
if(data[i].extra && data[i].extra.childs){
for(var j in data){
if(data[j].id == data[i].extra.childs){
data[i].child = data[j];
delete(data[j]);
break;
}
}
}
}
$scope.things = data;//then put the morphed JSON in the $scope.things
HTML 将是这样的。请注意,我在您的 JSON 中添加了一个有 child 的关键 child
<div class="thing" ng-repeat="thing in things">
<h1>{{thing.title}}</h1>
<p>{{thing.description}}</p>
<br/>
<div class="child" ng-if="things.child">
<p>{{thing.child.title}}</p>
<p>{{thing.child.description}}</p>
</div>
</div>
关于javascript - AngularJS 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32350655/