Reputation: 35
I've spent a while trying to find an elegant solution to this, whilst I have a solution that 'works' it doesn't feel like the easiest or correct way of doing things.
So, my question is...how can I dynamically load directives! For some context, below is how I was hoping I'd be able to get away with it! I've not included the routing or anything but the template loads and I assign the below controller with 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 as 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 that anyone can offer would be greatly appreciated, excuse me if I'm doing anything obviously stupid this is my first time round with Angular!
Upvotes: 2
Views: 606
Reputation: 2547
i hope this help you:
for explain: you have to $compile your directive when you want to use it in other directive like 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 as 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>
Upvotes: 2