Rendering AngularJS directives from an array of directive names in a parent directive or controller

I am trying to dynamically visualize directives based on an array of directive name configurations. Is this possible in angular? I also want these visualized directives to live inside the same parent dom element, and not everyone, getting a new wrapper (as with ng-repeat).

http://jsfiddle.net/7Waxv/

var myApp = angular.module('myApp', []); myApp.directive('one', function() { return { restrict: 'A', template: '<div>Directive one</div>' } }); myApp.directive('two', function() { return { restrict: 'A', template: '<div>Directive two</div>' } }); function MyCtrl($scope) { $scope.directives = ['one', 'two']; } <div ng-controller="MyCtrl"> <div ng-repeat="directive in directives"> <div {{directive}}></div> </div> </div> 

EDIT: After posting this question, I also tried:

 .directive('parentDirective', function () { return { restrict: 'A', replace: true, link: function (scope, element) { scope.directives = ['one', 'two']; for (var i = 0; i < scope.directives.length; i++) { element.prepend('<div ' + scope.directives[i] + '></div>') } } }; }); <div parent-directive></div> 

However, templates from predefined directives are not displayed.

+4
source share
2 answers

Here is what I came up with (it took a lot of time) ... The solution is quite universal, but you can change the $scope.directives as you wish, and the directives will be fabricated dynamically. You can also specify any specific property in the current area to get a list of directives.

Demo link

app.js

 var myApp = angular.module('myApp', []); myApp.directive('one', function() { return { restrict: 'E', replace: true, template: '<div>Directive one</div>' } }); myApp.directive('two', function() { return { restrict: 'E', replace: true, template: '<div>Directive two</div>' } }); myApp.directive('dynamic', function ($compile, $parse) { return { restrict: 'A', replace: true, link: function (scope, element, attr) { attr.$observe('dynamic', function(val) { element.html(''); var directives = $parse(val)(scope); angular.forEach(directives, function(directive) { element.append($compile(directive)(scope)); }); }); } }; }); function MyCtrl($scope) { $scope.directives = ['<one/>', '<two/>']; $scope.add = function(directive) { $scope.directives.push(directive); } } 

index.html

 <div ng-controller="MyCtrl"> <div dynamic="{{directives}}"></div> <button ng-click="add('<one/>')">Add One</button> <button ng-click="add('<two/>')">Add One</button> </div> 
+5
source

So, the second attempt would work if I used the $ compilation in the prescribed directives:

 .directive('parentDirective', function($compile) .... element.prepend($compile('<div ' + scope.directives[i] + '"></div>')(scope)); 
0
source

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


All Articles