使用嵌套对象时,如何在 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"]}
]},
];
我一直在使用 ng-switch 块,但是它对于嵌套项目变得站不住脚,就像上面的 Address 对象一样.
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!
推荐答案
我认为这可以帮助您.它来自我在 Google Group 关于树中的递归元素.
I think that this could help you. It is from an answer I found on a Google Group about recursive elements in a tree.
建议来自 Brendan Owen: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-switch 指令创建一个模板(就像您所做的那样,每种标签类型一个案例)并在末尾添加 ng-include(如果有任何子标签).
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屋!