带有动态模板的指令

时间:2016-01-20 15:20:56

标签: javascript angularjs

假设我有一个指令,它采用模型并使用ng-repeat打印所有模型的元素。类似的东西:

(function () {
    'use strict';

    angular
        .module('myDirective', [])
        .directive('myDirective', myDirective);

    function myDirective() {

        return {
            restrict: 'E',
            scope: {
                mlModel: '=',
            },
            template: '<ul><li ng-repeat="actor in mlModel">{{actor.code}} - {{actor.name}}</li></ul>'
        };
    }
})();

其他地方我有模特:

vm.testModel = [{
  'code' : 'ABC',
  'name' : 'A name'
}, {
  'code' : 'DCE',
  'name' : 'Another nane'
}];

并且指令以这种方式使用:

<my-directive ml-model="vm.testModel"></my-directive>

这很有效,我有一个PLNKR作为演示。该指令应该在不止一个地方使用,模型略有不同,例如我应该有这样的模型:

vm.testModel2 = [{
  'id' : '34234',
  'description' : 'A description'
}, {
  'id' : '456345',
  'description' : 'This is another description'
}];

结构相同,但现在code属性称为idname属性称为description。导致巨大问题的小差异,因为在指令中我已经硬编码了如何读取模型(即我写了{{actor.code}} - {{actor.name}})。

我会将模型读取的代码作为指令参数发送,并在指令的模板中使用它。类似的东西:

<my-directive ml-model="vm.testModel" ml-parser="{{actor.code}} - {{actor.name}}"></my-directive>
<my-directive ml-model="vm.testModel2" ml-parser="{{actor.id}} - {{actor.description}}"></my-directive>

这可能吗?我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您可以在指令的compile属性中实现它,因此请添加:

compile:function(element,attrs){
    element.find('li').append(attrs.mlParser);
}

PLNKR示例。

答案 1 :(得分:0)

我稍微修改了指令代码,看看:

function myDirective() {

        return {
            restrict: 'E',
            scope: {
                mlModel: '=',
            },
            link : function(scope, element, attrs){
              scope.view = [];

              scope.mlModel.forEach(function(actor){
                scope.view.push({name : actor[Object.keys(actor)[0]], value : actor[Object.keys(actor)[1]]});
              });
            },
            template: '<ul><li ng-repeat="actor in view">{{actor.name}} - {{actor.value}}</li></ul>'
        };
    }
相关问题