我有一个JSON对象,每个属性都有不同的名称,如下所示:
var definitions = {
foo: {
bar: {abc: '123'},
baz: 'def'
},
qux: {
broom: 'mop',
earth: {
tree: 'leaf',
water: 'fish'
},
fig: {
qwerty: 'olive'
}
},
blix: {
worm: 'dirt',
building: 'street'
}
... more nested objects
};
现在,我像这样显示这些数据:
<div class="type" ng-repeat="(key,val) in definitions">
<h4 ng-model="collapsed" ng-click="collapsed=!collapsed">{{key}}</h4>
<div ng-show="collapsed">{{val}}</div>
</div>
这是我的控制器:
App.controller('DefinitionsCtrl', function ($scope) {
$scope.definitions = definitions;
});
{{val}}
只是在单击属性各自的{{key}}
时显示属性的压缩字符串。我想进一步正确解析val
部分,因此例如foo
的嵌套属性(bar
和baz
)将分别有自己的div。但是,我想对所有嵌套值执行此操作。手动执行此操作不是一种选择(这是一个大文件)。
考虑到所有嵌套名称都不同,这可能吗?我是否必须创建自定义过滤器,或者这是我应该在控制器中处理的事情?
所以如果我理解正确,你想要一个递归的ng-repeat?最好的办法是创建自定义指令。
查看这个递归的示例指令:
.directive('collection', function () {
return {
restrict: "E",
replace: true,
scope: {
collection: '='
},
template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
}
})
.directive('member', function ($compile) {
return {
restrict: "E",
replace: true,
scope: {
member: '='
},
template: "<li>{{member.name}}</li>",
link: function (scope, element, attrs) {
// this is just un-compiled HTML, in the next step we'll compile it
var collectionSt = '<collection collection="member.children"></collection>';
if (angular.isArray(scope.member.children)) {
//compile and append another instance of collection
$compile(collectionSt)(scope, function(cloned, scope) {
element.append(cloned);
});
}
}
}
})
在这里看到它运行:http://jsbin.com/acibiv/4/edit 和一篇关于它的博客文章:http://sporto.github.io/blog/2013/06/24/nested-recursive-directives-in-angular/但是不要遵循博客文章中的代码,这是不正确的。他没有正确编译。
当然,这将需要您进行大量定制。而不是检查"子",你必须检查你的值是否是一个对象。