我想将我的SPA传递给JSON数组,并根据数组中的内容呈现控件和指令。
我根据此处的答案提供了所有控件渲染; plunker link
但是,我也有我想要渲染的自定义指令,但我不想在HTML中指定它们中的每一个。相反,我想做一些像;
<div ng-if="field.type=='directive'" class="form-group {{field.css}}">
<{{field.directive}}></{{field.directive}}>
</div>
然后在JSON对象中指定要呈现的指令;
app.directive("testDirective", function(){
return {
restrict: 'E',
scope: {},
template: '<h2>This is a custom directive to show that we can render these also.</h2>',
replace: true
};
})
将该指令添加到要呈现的控件列表中;
fields :
[
{type: "directive", directive:"test-directive", name: "td1", data: ""},
我创建的代码只是输出;
<test-directive>
作为文本,而不是作为控件本身。
有什么想法吗?
答案 0 :(得分:1)
作为@charlietfl和@Saurabh Agrawal,角度2&amp;但是,仍然供你参考,我已经在角度1中做了一个解决方案。现在模板将基于JSON中的数据类型进行渲染。
HTML code:
<body ng-app="dynamicDirective" ng-controller="MyModule">
<div ng-repeat="field in entity.fields">
<dynamic-field data='field'> </dynamic-field>
<br/>
</div>
</body>
脚本代码:
app.directive('dynamicField', function() {
return {
restrict: 'E',
scope: {
data: "="
},
templateUrl: 'template.html',
link: function(scope, element, attrs) {
}
}
});
这是模板html文件,其中字段将根据JSON数据中的类型进行呈现。请参阅以下链接
<!-- Text Template -->
<div ng-if="data.type === 'text'">
{{data.name}} <input type="text"/>
</div>
<!-- Radio Template -->
<div ng-if="data.type === 'radio'">
{{data.name}}
<div ng-repeat="option in data.options">
<input type="radio" value="option.name" />{{option.name}}
</div>
</div>
<!-- Email Template -->
<div ng-if="data.type === 'email'">
{{data.name}} <input type="text"/>
</div>
<!-- Password Template -->
<div ng-if="data.type === 'password'">
{{data.name}} <input type="password"/>
</div>
<!-- Select Template -->
<div ng-if="data.type === 'select'">
{{data.name}} <select><option ng-repeat="option in data.options">
{{option.name}}</option></select>
</div>
<!-- Checkbox Template -->
<div ng-if="data.type === 'checkbox'">
{{data.name}}
<div ng-repeat="option in data.options">
<input type="checkbox" value="option.name" />{{option.name}}
</div>
</div>
希望有所帮助:)