我如何使用嵌套的对象时使AngularJS递归模板? [英] How can I make recursive templates in AngularJS when using nested objects?
问题描述
我想从一个JSON对象,其中包含表单元素的嵌套组动态生成的表单:
I'm trying to build a form dynamically from a JSON object, which contains nested groups of form elements:
$scope.formData = [
{label:'First Name', type:'text', required:'true'},
{label:'Last Name', type:'text', required:'true'},
{label:'Coffee Preference', type:'dropdown', options: ["HiTest", "Dunkin", "Decaf"]},
{label: 'Address', type:'group', "Fields":[
{label:'Street1', type:'text', required:'true'},
{label:'Street2', type:'text', required:'true'},
{label:'State', type:'dropdown', options: ["California", "New York", "Florida"]}
]},
];
我一直在使用纳克开关块,但它变得站不住脚嵌套的项目,如上面的地址对象。
I've been using ng-switch blocks, but it becomes untenable with nested items, like in the Address object above.
这里的小提琴:
http://jsfiddle.net/hairgamiMaster/dZ4Rg/
如何以最佳方式处理这个问题的嵌套任何想法?非常感谢!
Any ideas on how to best approach this nested problem? Many thanks!
推荐答案
我认为这可以帮助你。这是从我的回答对有关递归元素谷歌集团发现一颗树。
I think that this could help you. It is from an answer I found on a Google Group about recursive elements in a tree.
该建议是由布伦丹·欧文: http://jsfiddle.net/brendanowen/uXbn6/8/
The suggestion is from Brendan Owen: http://jsfiddle.net/brendanowen/uXbn6/8/
<script type="text/ng-template" id="field_renderer.html">
{{data.label}}
<ul>
<li ng-repeat="field in data.fields" ng-include="'field_renderer.html'"></li>
</ul>
</script>
<ul ng-controller="NestedFormCtrl">
<li ng-repeat="field in formData" ng-include="'field_renderer.html'"></li>
</ul>
提出的解决方案是关于使用采用NG-include指令称自己如果当前元素有孩子的模板。
The proposed solution is about using a template that uses the ng-include directive to call itself if the current element has children.
在你的情况,我会尝试创建一个NG-开关指令(每像你这样类型的标签一例)的模板,并在末尾添加了NG-包括,如果有任何一个孩子的标签。
In your case, I would try to create a template with the ng-switch directive (one case per type of label like you did) and add the ng-include at the end if there are any child labels.
这篇关于我如何使用嵌套的对象时使AngularJS递归模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!