Kolby
Kolby

Reputation: 2865

Is it possible to dynamically load directives in a template?

I'm making a widget system and I plan to have each widget be it's own directive. I want to be able to pass the directives that should be used from my controller to my view via an array. This is what my code currently looks like:

app.controller('showDashboard', function ($scope){
   $scope.widgets = ['widget1', 'widget2', 'widget3'];
});

In View:

<article ng-repeat="widget in widgets" class="widget">
    <div {{widget}}></div>
</article>

Directive:

app.directive('widget1', function (){
    return {
        restrict: "A",
        templateUrl: 'testWidget.html'
    };
}).directive('widget2', function (){
    return {
        restrict: "A",
        templateUrl: 'testWidget.html'
    };
}).directive('widget3', function (){
    return {
        restrict: "A",
        templateUrl: 'testWidget.html'
    };
});

Upvotes: 2

Views: 64

Answers (2)

Whisher
Whisher

Reputation: 32716

It can be improved but just to get the idea

//html
<div wrapper mydir="widget"></div>
//js
.directive('wrapper', function ($compile){
                return {
                    restrict: "A",
                    scope: {
                        mydir: "="
                    },
                    link: function ( scope, element ) {
                        var html = '<test '+scope.mydir+'></test>';
                        var compiled = $compile( html )( scope );
                        element.append(compiled);
                    }
                }
            })

Upvotes: 1

Josh
Josh

Reputation: 44906

So rather than make the directive itself the widget, why not use ng-include to load in the templates which can themselves contain directives, controllers etc...

app.controller('showDashboard', function ($scope){
   $scope.widgets = ['widget1.html', 'widget2.html', 'widget3.html'];
});

<article ng-repeat="widget in widgets" class="widget">
    <div ng-include="widget"></div>
</article>

Here is a jsFiddle with an example.

And here is an updated fiddle that shows a slightly more complex widget with a controller.

Upvotes: 4

Related Questions