假設我有一個指令,它使用一個模型並用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}}
)。
我會將模型讀取的代碼作爲指令參數發送,並在指令的模板中使用它。例如:
這可能嗎?我怎樣才能做到這一點?
智能解決方案。做得好! –