2

I have a directive defined as

Application.Directives.directive('listview', function() {
    return {
        restrict: 'EAC',
        templateUrl: 'directives/listview/view.html'
    };
});

And then want to include it from the main view like this

<div class="{{directiveName}}">
</div>

where directiveName equals "listview". However, it does not work. It generates the below code, but the listview directive does not get loaded

<div class="listview">
</div>

Yet, when I type the above generated code directly into the main template, it does load the directive. How come? How can I make it work?

1 Answer 1

2

So I found a way. What you'd want is something like this

<div {{directiveNameInScope}}></div>

But again, that doesn't work. So I created a directive to do it for you. It works like

<div loaddirective="directiveNameInScope"></div>

where the loaddirective directive looks like

Application.Directives.directive('loaddirective', function($compile) {
    return {
        restrict: 'A',
        scope: { loaddirective : "=loaddirective" },
        link: function($scope, $element, $attr) {
            var value = $scope.loaddirective;
            if (value) {
                // Load the directive and make it reactive
                $element.html("<div "+value+"></div>");
                $compile($element.contents())($scope);
            }
        },
        replace: true
    };
});

I put it up on github here: https://github.com/willemmulder/loaddirective

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.