我正在 AngularJS 中实现一个表单构建器,需要在运行时插入和重新排序指令。甚至不知道从哪里开始寻找 - 所有示例似乎都只展示了指令的静态树。实现动态行为的两个选项是:a)动态编译和插入模板,b)使用所有可能指令的巨大 ng-switch。两种方式都很丑。
任何人都可以提出更好的实施方案吗?
下面是我认为 formbuilder 在理想世界中应该如何看待的 JS 和 html 代码,请帮我填写 3 个 TODO 实例。
JSFiddle JavaScript:
angular.module('components', [])
.directive('checkbox', function() {
return {
restrict: 'E',
template: '<div class=f><input type=checkbox>{{name}}</input></div>'
};
})
.directive('textfield', function() {
return {
restrict: 'E',
template: '<div class=f><input type=text placeholder="{{name}}"></input></div>'
};
})
function FormBuilder($scope, $locale) {
$scope.title = 'test form';
$scope.fields = [];
$scope.add_checkbox = function() {
console.log('adding checkbox');
var field = null; // TODO: how do I instantiate a directive?
$scope.fields.push(field);
};
$scope.add_textfield = function() {
console.log('adding textfield');
var field = null; // TODO: how do I instantiate a directive?
$scope.fields.push(field);
};
}
HTML:
<div ng-app=components ng-controller=FormBuilder>
<button ng:click="add_checkbox()">new checbox</button>
<button ng:click="add_textfield()">new text field</button>
<h3>{{ title }}</h3>
<checkbox></checkbox>
<textfield></textfield>
<div ng:repeat="field in fields">
<!-- TODO field.get_html() - how? -->
</div>
</div>