使用指令作用域变量呈现的动态模板
Dynamic templates rendered using directive scope variables
试图找到一种方法,根据JSON文档中指定的Type变量,用不同的控件呈现表单。这个表单将根据用户输入生成,所以我们不知道需要呈现什么问题类型。我们将定义类型,但它们可以按照用户的任何顺序出现。
{
"Name": "Getting to know you.",
"Id": "870tVcee8irPLdhi14fSZw==",
"Controls": [
{
"Type": "Text",
"Label": "First Name",
"Id": "vF4z8YcSlpJGsF9fDw5TpA==",
"Color": "FFFFFF",
"Required": "True",
"Validaion": "False",
"ValidationRegEx": "",
"ErrorText": ""
},
{
"Type": "Picklist",
"Label": "Last Name",
"Id": "vF4z8YcSlpJGsF9fDw5TpA==",
"Color": "#CCCCCC",
"Required": "True",
"Validaion": "False",
"ValidationRegEx": "",
"ErrorText": "",
"PicklistVals": ["1","3","5"]
}
]
}
指令需要读取控件类型,然后将其传递给指令,以确定要呈现的模板。
<div ng-repeat="control in section.Controls">
<input-parser ele="{{control}}"></input-parser>
</div>
app.directive('inputParser', function() {
function getTemplate (control) {
var template = '';
switch(control.Type) {
case 'Text':
template = '<form style="color:' + control.Color + '">template2</form>';
break;
case 'Picklist':
template = '<form style="color:' + control.Color + '">template2</form>';
break;
}
return template;
}
return {
restrict: "E",
scope: {
control: '@'
},
template: function() {
return getTemplate(control));
}
}
两个问题:
您可以访问动态加载的指令的template属性中的作用域变量吗?我似乎只能硬编码它们,因为如果解析的话,绑定不会在指令之前设置。
这是呈现需要访问传递到指令中的信息的动态模板的好方法吗。我应该只访问根作用域而忘记作用域变量吗?
如果您的input-parser
指令只是呈现表单,而不做任何其他操作,那么不如考虑使用ng-include
,并将所有模板作为分部放置。
演示
<ng-include ng-repeat="control in section.Controls" src="control.type + '.html'"></ng-include>
但是,如果您的input-parser
指令确实有某种行为,您希望在所有模板中共享,那么您可以使用上面的ng-include
作为模板。
Javascript
.directive('inputParser', function() {
return {
restrict: 'E',
scope: {
control: '='
},
template: '<ng-include src="''form'' + control.type + ''.html''"></ng-include>'
// controller: function() {}, // attach your controller behaviour
// link: function() {} // attach your element behaviour
};
});
HTML
<input-parser ng-repeat="control in section.Controls" control="control"></input-parser>
相关文章:
- 向动态生成的DOM添加Angular自定义指令
- AngularJs从列表中动态创建指令
- AngularJS 指令的动态选项
- 如何动态禁用Angular指令
- 不适用于动态数据的Angular指令来自$http
- 动态更新Angular2指令中自定义属性的值
- 动态网格作为自定义指令
- 动态指令:模板网址
- Angular JS - 具有默认行为的动态指令
- 使用AngularJS加载动态指令-错误:访问受限URI被拒绝
- AngularJS多个动态指令绑定
- AngularJS-使用ng重复的动态指令
- 使用应用程序级解析AngularJS的动态指令模板
- 如何使用 $interpolate 函数从 JSON 添加动态指令名称
- 简单动态指令AngularJS
- 在AngularJS的另一个指令模板中添加动态指令
- 来自指令模板的动态指令
- 简单的动态指令(带有动态控制器和作用域)
- 角度 JS 动态指令模板
- Angularjs:动态指令