Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Tag Generation in Angular

Tags:

angularjs

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

  • make a directive that generates tags
  • continue using ng-include as I am
  • use another method
like image 644
Logan Murphy Avatar asked Mar 18 '23 13:03

Logan Murphy


1 Answers

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'];

like image 55
letiagoalves Avatar answered Mar 30 '23 07:03

letiagoalves