2016-01-20 112 views
1

假设我有一个指令,它使用一个模型并用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属性被称为id,并name属性称为description。小的差异,导致巨大的问题,因为在指令内我已经硬编码如何读取模型(即我写了{{actor.code}} - {{actor.name}})。

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

这可能吗?我怎样才能做到这一点?

回答

1

您可以从该指令compile属性实现它,所以加:

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

PLNKR例子。

+0

智能解决方案。做得好! –

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>' 
     }; 
    } 
+0

这将解决*这个*问题,但在野外太脆弱了:) –