我有一个指令列表(通常是表单字段和自定义表单控件)。现在我将从后端获取指令名列表以用于构建表单。
它基本上创建了一个动态表单,我不知道表单中的所有表单字段是什么(它取决于我从后端获得的JSON配置文件)。
示例JSON:
field1 : {
type: 'text',
directive : 'directive1'
},
field2: {
type : 'dropdown',
directive : 'dropdown-directive'
}
我可以在AngularJS中做类似的事情吗?如果可能的话,我该怎么办?
答案 0 :(得分:1)
对范围使用$ compile服务。这将允许您编译可以附加到容器的角度代码。
参见jsfiddle:http://jsfiddle.net/p8jjZ/1/
HTML:
<div ng-app="myApp" ng-controller="MainController">
<div custom-elements="myData.elements"></div>
<p>{{user}}</p>
</div>
JavaScript的:
var mod = angular.module("myApp", []);
mod.controller("MainController", function ($scope) {
$scope.myData = {};
$scope.myData.elements = {
field1 :{ type: 'text', directive : 'directive1' },
field2: { type : 'dropdown', directive : 'dropdown-directive' }
};
});
mod.directive("customElements", function ($compile) {
return {
restrict: "A",
scope: {
customElements: "="
},
link: function (scope, element, attrs) {
var prop,
elems = scope.customElements,
currElem,
compiled;
for (prop in elems) {
currElem = elems[prop];
console.log("Working on " + prop);
//compile input against parent scope. Assuming directives are attributes, but adapt to your scenario:
compiled = $compile('<div ' + currElem.directive + '></div>')(scope.$parent);
//append this to customElements
element.append(compiled);
}
}
}
});
mod.directive("directive1", function () {
return {
restrict: "A",
template: '<div>Whoa! I am directive 1<br><input type="text" ng-model="user.name"></div>'
}
});
mod.directive("dropdownDirective", function () {
return {
restrict: "A",
template: '<div>I am another directive<br><select ng-model="user.color"><option value="blue">blue</option><option value="green">Green</option></div>'
}
});
customElement指令只是创建指令,就好像它是元素的属性一样。这是一个非常简单的示例,但是应该让您开始了解您要执行的操作,您可以在其中更新构建元素/指令的逻辑。