我想用 Angular 编写一个表单构建器应用程序。 该应用程序将允许用户使用拖放元素构建简单的 HTML 表单。
我认为将元素模板存储为单独的 html 文件或字符串会很好。
例如,如果我有以下数据:
$scope.formFields = [
{type: "fTextbox", name: "textbox1", label: "First name"},
{type: "fDropdown", name: "dropdown1", label: "Country"},
{type: "fCheckbox", name: "terms1", label: "TermsAndConditions"},
...
];
我还可以在某个地方有一个字典来存储模板并将它们映射到表单元素。
{
fTextbox: "/templates/elements/textbox.html",
fDropdown: "/templates/elements/dropdown.html",
fCheckbox: "/templates/elements/checkbox.html",
...
}
我将如何循环遍历它并将正确的模板附加到 View 中?
[编辑] 我只需要以 Angular 方式完成此类任务的一般方法。 到目前为止,我只遇到了模板的 ng-switch,但这不是一个理想的解决方案,因为可能有很多类型的表单元素,并且模板会变得非常困惑。
最佳答案
使用ng-include
根据名称动态注入(inject)模板,例如
<div ng-include='template.fTextbox'/>
<div ng-include='template.fCheckbox'/>
您也可以编写指令,但您仍然需要将它们包装到 ng-include
中。看我的回答AngularJS - how to have a directive with a dynamic sub-directive
关于javascript - 在 AngularJS Controller 内的循环中渲染和注入(inject)动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21989014/