2016-01-20 106 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

這將解決*這個*問題,但在野外太脆弱了:) –