Javascript 使用ng repeat获取具有不同名称的嵌套对象的值
我有一个JSON对象,每个属性有不同的名称,如下所示:Javascript 使用ng repeat获取具有不同名称的嵌套对象的值,javascript,json,angularjs,Javascript,Json,Angularjs,我有一个JSON对象,每个属性有不同的名称,如下所示: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fish' }, fig: { qwerty: 'olive' } }, blix: { worm:
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>
{{val}}
单击相应的{{key}}
时,仅显示属性的压缩字符串。我想进一步正确地解析val
部分,因此,例如foo
的嵌套属性(bar
和baz
)将分别具有自己的div。但是,我希望对所有嵌套值执行此操作。手动执行此操作不是一个选项(这是一个巨大的文件)
考虑到所有嵌套名称都不同,这可能吗?我需要创建一个自定义过滤器吗,或者这是我应该在控制器中处理的吗?因此,如果我理解正确,您希望递归ng重复吗?最好是创建自定义指令 查看这个递归的示例指令:
.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);
});
}
}
}
})
.directive('collection',function(){
返回{
限制:“E”,
替换:正确,
范围:{
集合:'='
},
模板:“
”
}
})
.directive('member',function($compile){
返回{
限制:“E”,
替换:正确,
范围:{
成员:'='
},
模板:“{{member.name} ”,
链接:函数(范围、元素、属性){
//这只是未编译的HTML,下一步我们将编译它
var collectionSt='';
if(angular.isArray(scope.member.children)){
//编译并附加集合的另一个实例
$compile(collectionSt)(作用域,函数(克隆,作用域){
元素。追加(克隆);
});
}
}
}
})
在此处查看它的运行情况:以及一篇关于它的博客文章:
但是不要遵循博客文章中的代码,这是不正确的。他没有正确地编译
当然,这需要您进行大量定制。不要检查“children”,你必须检查你的值是否是一个对象。我认为H4标签上的
ng模型
甚至不起任何作用。ng点击
只是在每个ng重复项范围上设置折叠
,第一次创建它。谢谢!也很有帮助。
.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);
});
}
}
}
})