Idov
Idov

Reputation: 5124

angularJS - variable component templates

Is it possible to define a variable template for a component in angularJS 1.6? Something like this:

<div class="test">
    <{{$ctrl.GetElement()}}> 
</div>        

for cases in which I want to decide in runtime what the template be like.

Is there a way to do it?

Upvotes: 0

Views: 674

Answers (1)

Jukebox
Jukebox

Reputation: 1603

Here is a simple example of a "variable template" using $compile. Let's define a "generator" directive which will be able to generate other directives:

app.directive('createDirective', function($compile) {
    return {
        scope: {
            directiveName: '@'
        },
        link: function(scope, element) {
            var newHtml = '<' + scope.directiveName +'></ '+ scope.directiveName +'>';
            element.append($compile(newHtml)(scope));
        }
    };
});

This "generator" directive takes in a string (via the attribute "directive-name"), assembles new HTML, compiles it, and appends the resulting HTML to the generator directive.

I've defined a separate directive named "Hello", which I want to be called dynamically from the generator directive:

app.directive('hello', function() {
    return {
        restrict: 'E',
        link: function(scope, element) {
            element.append("Hello!");
        }
    }
});

Now, we can use the generator directive to compile the "Hello" directive

<div create-directive directive-name="hello"></div>

which results in this generated HTML

<hello class="ng-scope">
    <!-- hello-->
    Hello!
</hello>

In addition, we can pass a variable from a controller to the generator directive in a similar way:

app.controller('MainCtrl', function($scope) {
    $scope.newDirective = "from-controller";
});

And in the HTML:

<div create-directive directive-name="{{newDirective}}"></div>

Be sure to take a look at the $compile documentation.

Demo

Upvotes: 1

Related Questions