有没有一种方法可以在 AngularJS View 中执行嵌套循环而不创建隐藏的虚拟元素?
像这样:
<ul>
<li ng-repeat="gem in activeHero.gems"
ng-repeat="(key, value) in gem.attributes"
ng-repeat="attr in value">
{{attr.text}}
</li>
</ul>
或者这个
<ul>
<li ng-repeat-start="gem in activeHero.gems"
ng-repeat-start="(key, value) in gem.attributes"
ng-repeat="attr in value">
{{attr.text}}
</li ng-repeat-end
ng-repeat-end>
</ul>
AFAIK 这些都不可能。
我基本上希望我的 HTML 具有与其所基于的 JSON 不同的结构。 我怎么能做到这一点?有没有办法在没有 HTML 元素的情况下在 View 内创建循环?
上面的例子会像这样遍历 JSON 结构:
JSON(为了清楚起见,去掉了很多)
"activeHero" = {
"gems" : [ {
"attributes" : {
"primary" : [ {
"text" : "+220 Intelligence"
} ],
"secondary" : [ ],
"passive" : [ ]
}
}, {
"attributes" : {
"primary" : [ {
"text" : "+220 Intelligence"
} ],
"secondary" : [ ],
"passive" : [ ]
}
}, {
"attributes" : {
"primary" : [ {
"text" : "+160 Intelligence"
} ],
"secondary" : [ ],
"passive" : [ ]
}
} ]
}
(这是来自暴雪 API 的视频游戏“暗黑破坏神 3”的实际 JSON 响应)
最佳答案
尝试在渲染前格式化你的 json;
$scope.formattedData = [];
angular.forEach(activeHero.gems, function(value, key){
var item = {
//set filed you want
}
angular.forEach(value.atrtibutes, function(value2, key2){
item['propyouwant'] = value2[propyouwant]
angular.forEach(value2.primary, function(value3, key3){
item['propyouwant'] = value3[propyouwant]
$scope.formattedData.push(angular.extend({}, item));
})
})
})
//now you can render your data without somersould
编辑
为了提高性能,避免使用 Angular 扩展;
$scope.formattedData = [];
angular.forEach(activeHero.gems, function(value, key){
angular.forEach(value.atrtibutes, function(value2, key2){
angular.forEach(value2.primary, function(value3, key3){
//start build your item here
var item = {
prop1: value['prop'],
prop2: value2['prop']
}
//not required extend item;
$scope.formattedData.push(item);
})
})
})
关于javascript - AngularJS 在同一个元素上嵌套了 ngRepeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782121/