我正尝试在AngularJS中创建表单构建器。整个形态结构在一个JSON对象,定义如下:在AngularJS中动态更改视图
form = {
"title": "Some form title", // Title of the field
"fieldsets": [ // Each form is composed of several fieldsets
{
"title": "First fieldset", // Title of the fieldset
"fields": [ // Each fieldset is composed of several fields
{
"title": "First field", // Title of the field, displayed in a label
"type": "text" // Type of the field which determines which partial to load
},
{
"title": "Second field",
"type": "date"
},
]
},
{
"title": "Second fieldset",
"fields": [
{
"title": "First field",
"type": "text"
},
{
"title": "Second field",
"type": "date"
},
]
}
]
}
我得到这样的一个JSON对象上面,然后呈现在一个页面像这样(玉模板):
h5 {{ form.title }}
div(ng-repeat="fs in form.fieldsets")
fieldset
legend {{ fs.title }}
div(ng-repeat="field in fs.fields")
myfield(field="field")
myfield
是一个自定义指令,用于解析每个字段并根据类型呈现不同的部分。这里是代码:
var appFilters = angular.module('appComponents', []);
appFilters.directive('myfield', ['$compile', '$http', '$templateCache', function($compile, $http, $templateCache){
var getTemplate = function(contentType) {
return $http.get('partials/' + contentType + '_field', {cache: $templateCache});
// I get the partials here, for example for a field of type text, I load text_field.jade
};
var linker = function(scope, element, attrs){
scope.edit_field = function(field) {
field.type = "template";
};
var loader = getTemplate(scope.field.type);
var promise = loader.success(function(html) {
element.html(html);
}).then(function(response) {
element.replaceWith($compile(element.html())(scope));
});
};
return {
restrict: 'E',
scope: {
field:'='
},
link: linker
};
}]);
我有几个partials。它们都从一个基本模板继承,名为field.jade
。这里是基本模板和另一个从它继承:
field.jade:(对于其他的partials基本模板):
div
block _title
div
div
block _label
label {{ field.title }}:
div
block _field
div
block _controls
a.control(ng-click="edit_field(field)") Edit
text_field.jade:(部分为领域类型文字)
extend field
block _field
input(type="text")
template_field.jade:(部分为字段,当它们在编辑模式下)
extend field
block _label
input(type="text", ng-model="field.title")
// The user can edit the field label here
block _field
select
// Here the user can select from several different field types
现在,当用户点击按钮Edit
,field.type
被改变为template
,我想AngularJS到代替加载主视图(如text_field.jade
)的template_field.jade
视图。
有没有人有任何想法如何告诉AngularJS重新加载templated_field.jade
部分呢? P:我想为此创建一个小提琴,但由于它太复杂了,我不得不导入几个不同的文件来运行它,所以我放弃了创作小提琴。
认为您需要在此处添加更多代码。也许是一个小提琴? –
@Baszz我在这里增加了更多细节。 –