javascript - AngularJS - Dynamic Directives using ng-repeat -


i've spent while trying find elegant solution this, whilst have solution 'works' doesn't feel easiest or correct way of doing things.

so, question is...how can dynamically load directives! context, below how hoping i'd able away it! i've not included routing or template loads , assign below controller ng-controller.

app.js

angular.module('myapp', [])  .controller('somecontroller', ['$scope', function($scope) {   $scope.directives = ['mydirectivea', 'mydirectiveb']; }])  .directive('mydirectivea', function() {   return {     template: '<p>directive a, exciting.</p>'   }; })  .directive('mydirectiveb', function() {   return {     template: '<p>directive b, equally exciting.</p>'   }; }); 

template.html

<div ng-controller="somecontroller">   <div ng-repeat="directive in directives">      <x-directive></x-directive> // attempt 1     <x-{{directive}}></x-{{directive}}> // attempt 2     <{{'x-' + directive}}></{{'x-' + directive}}> // attempt 3    </div> </div> 

any advice can offer appreciated, excuse me if i'm doing stupid first time round angular!

i hope you:

for explain: have $compile directive when want use in other directive ngrepeat or other custom directive...

        angular.module('myapp', [])            .controller('somecontroller', ['$scope', function ($scope) {              $scope.directives = ['my-directive-a', 'my-directive-b'];          }])            .directive('directive', function ($compile) {              return {                  restrict: "a",                  scope: {                      set: "="                  },                  link: function (scope, element) {                      element.html("<div class=\" "+ scope.set +" \"></div>");                      $compile(element.contents())(scope);                  }              };          })            .directive('mydirectivea', function () {              return {                  restrict: "c",                  template: '<p>directive a, exciting.</p>'              };          })            .directive('mydirectiveb', function () {              return {                  restrict: "c",                  template: '<p>directive b, equally exciting.</p>'              };          });
<!doctype html>  <html ng-app="myapp">  <head>      <title></title>  </head>  <body ng-controller="somecontroller">            <div ng-repeat="directive in directives">          <div directive set="directive"></div>      </div>        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>  </body>  </html>


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -