0

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?

2
  • you might looking for $compile docs.angularjs.org/api/ng/service/$compile Commented Feb 17, 2017 at 18:59
  • This is possible, but is totally against the design goals of angular. This is the realm of Directives and Components; This kind of code with functions that execute inside expressions will grind your app performance wise. Commented Feb 17, 2017 at 23:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.