在AngularJS的分部中动态包含指令
Dynamically including directive in an AngularJS partial
我有一个指令列表(通常是表单字段和自定义表单控件)。现在,我将从后端获取指令名称列表,以用于构建表单。
它基本上创建了一个动态表单,我不知道表单中所有的表单字段是什么(这取决于我从后端获得的JSON配置文件)。
示例JSON:
field1 : {
type: 'text',
directive : 'directive1'
},
field2: {
type : 'dropdown',
directive : 'dropdown-directive'
}
我能在AngularJS中做类似的事情吗?如果可能的话,怎么做?
针对作用域使用$compile服务。这将允许你编译可以添加到容器中的angular代码。
参见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指令只是创建了一个指令,就好像它是一个元素的属性一样。这是一个非常简单的例子,但应该让你开始做你想做的事情,你可以更新相应的逻辑来构建元素/指令。
相关文章:
- javascript 在着陆页中动态包含关键字
- 如何在开发和生产中动态包含脚本
- 基于屏幕大小的动态包含文件不起作用
- 基于浏览器特性动态包含PHP
- 异步JavaScript动态包含
- 如何从动态包含对象的变量生成对象数组
- 动态包含模板角度指令
- 动态包含javascript文件的安全方法
- 来自动态包含的 js 文件的 Dreamweaver 代码提示
- 无法在ng重复中动态包含角度模板
- 动态包含的Javascript和依赖项
- 调用窗口对象初始化(页面中动态包含iframe)
- 在javascript文件中动态包含javascript代码
- 动态包含javascript文件,然后动态调用函数
- 通过JavaScript在页眉或HTML中动态包含脚本元素
- 动态包含外部Javascript文件
- 无法使用jQuery找到动态包含的DOM元素
- 通过 apache 服务器内部的服务器端过滤,在 SVG 中动态包含 JavaScript
- 动态包含角度指令
- 在AngularJS的分部中动态包含指令