Chad Johnson
Chad Johnson

Reputation: 21895

Dynamically insert directives using meta data in AngularJS?

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?

Upvotes: 0

Views: 540

Answers (1)

LostInComputer
LostInComputer

Reputation: 15420

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

Upvotes: 2

Related Questions