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"];
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}}>
Right now as an alternative I do the following
<div ng-include="component + '.html'" ng-repeat="component in components track by $index"></div>
Which basically does what the directive would do with the templateUrl parameter. Should I
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.
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>
being components
an array of strings in the scope as in your question:
$scope.components = ['textbox', 'radio', 'checkbox', 'label'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With