Generate dynamic tag in Angular

I am trying to dynamically generate a form using an array containing a bunch of directive names

$scope.components = ["textbox", "textbox", "radio", "checkbox", "label"];

I want to create tags with these names using angular. for instance

<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}}> 

Now, as an alternative, I am doing the following

<div ng-include="component + '.html'" ng-repeat="component in components track by $index"></div>

Which basically does what the directive will do with the templateUrl parameter. Should I

  • create a directive that generates tags
  • keep using ng-include as i
  • use another method
+3
source share
1 answer

You cannot generate an element tag dynamically using only angular expressions. However, you can create a custom directiveone to do this for you.

: (: DOM, )

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 , :

$scope.components = ['textbox', 'radio', 'checkbox', 'label'];

+7

Source: https://habr.com/ru/post/1653095/


All Articles