在AngularJS中使用元数据动态插入指令?

时间:2014-03-14 21:18:25

标签: javascript angularjs angularjs-directive

我想定义元数据,它将根据“类型”值动态使用正确的指令:

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

然后

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

我创建了一个jsfiddle here。到目前为止,我没有成功

这可能吗?我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

以下是解决问题的另一种方法:

使用ngSwitch在类型和指令之间进行映射。

<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

但是如果你真的需要在元数据中定义指令,你可以添加一个指令来生成带有相应指令的div元素

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