Angular中的动态标签生成 [英] Dynamic Tag Generation in Angular
问题描述
我正在尝试使用包含一堆指令名称的数组动态生成表单
I am trying to dynamically generate a form using an array that contains a bunch of directive names
$scope.components = ["textbox", "textbox", "radio", "checkbox", "label"];
我想使用angular来生成具有这些名称的标签.例如
I want to generate tags with these names using angular. For example
<textbox></textbox>
<textbox></textbox>
<radio></radio>
<checkbox></checkbox>
<label></label>
<--THE FOLLOWING DOESN'T WORK BUT WOULD BE COOL IF IT DID-->
<{{component}} ng-repeat="component in components track by $index"></{{component}}>
现在我可以替代
<div ng-include="component + '.html'" ng-repeat="component in components track by $index"></div>
基本上,该指令将执行templateUrl参数所执行的操作.我应该
Which basically does what the directive would do with the templateUrl parameter. Should I
- 制定一个生成标签的指令
- 按原样继续使用ng-include
- 使用其他方法
推荐答案
您不能仅使用角度表达式来动态生成元素标签.但是,您可以创建一个自定义directive
来为您完成此工作.
You can't generate tag of elements dynamically using only angular expressions. However you can create a custom directive
to do that work for you.
概念证明:((演示:检查DOM树以查看生成的元素)
Proof of concept: (Demo: inspect DOM tree to see generated elements)
angular.module('MyModule').directive('dynamicTag', function($compile) {
return {
restrict: 'E',
scope: {
components: '&components'
},
link: function($scope, $element) {
var components = angular.isFunction($scope.components) ? $scope.components() : [];
var domElements = [];
angular.forEach(components, function(c) {
var domElement = document.createElement(c);
$compile(domElement)($scope);
domElements.push(domElement);
});
$element.replaceWith(domElements);
}
};
});
HTML
<dynamic-tag components="components"></dynamic-tag>
components
在您的问题中是作用域中的字符串数组:
being components
an array of strings in the scope as in your question:
$scope.components = ['textbox', 'radio', 'checkbox', 'label'];
这篇关于Angular中的动态标签生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!