Dynamic Tag Generation in Angular

后端 未结 1 597
执笔经年
执笔经年 2021-01-06 11:02

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

$scope.components = [\"textbox\", \"textbox\", \"radio\",          


        
相关标签:
1条回答
  • 2021-01-06 11:05

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

    0 讨论(0)
提交回复
热议问题