0

I'd like to define meta data which will dynamically use the correct directive based on a "type" value:

$scope.items = [
    {
        type: 'directive-one',
        value: 'One'
    },{
        type: 'directive-two',
        value: 'Two'
    },{
        type: 'directive-three',
        value: 'Three'
    }
];

and then

<li ng-repeat="item in items" {{type}}>
    {{value}}
</li>

I've created a jsfiddle here. So far I've had no success

Is this possible? How would I accomplish this?

1 Answer 1

2

Here is an alternative way of solving the problem:

Use ngSwitch to map between type and directive.

<li ng-repeat="item in items">
    <div ng-switch on="item.type">
        <div ng-switch-when="type-one" directive-one>
        </div>
        <div ng-switch-when="type-two" directive-two>
        </div>
        <div ng-switch-when="type-three" directive-three>
        </div>
    </div>
</li>

See jsfiddle

But if you really need to define the directive in the metadata, you can add a directive that will generate the div element with the appropriate directive

angular.module('myApp').directive('dynamicDirective', function($compile) {
    return {
        restrict: 'A',
        link: function (scope, ele) {
            //add a child div element that contains the directive specified in the type property
            var itemEl = angular.element('<div>').attr(scope.item.type,'');
            $compile(itemEl)(scope);
            ele.append(itemEl);
        }
    };
});

See jsfiddle

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

3 Comments

Thanks for the ideas! I think the second approach would lead to a monolithic directive supporting what might be better as multiple directives. For instance, this may result in <formelement type="text"></formElement> and <formelement type="dropdown"></formElement> rather than separate directives encapsulating their own specific functionalities.
The second approach just compiles the HTML so that the directive attached to the element is chosen dynamically. There will still be multiple (separate) directives just like to asked. See jsfiddle.net/h8xHe/3
Well, I created an alternate solution using ng-include and templates here jsfiddle.net/C5TpR/5 but I think yours is superior because it doesn't require separate templates in addition to directives. So, thanks!

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.