假设我有一个指令,它采用一个模型并使用 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}}
).
我会将模型读取的代码作为指令参数发送,并在指令的模板中使用它。像这样的东西:
<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>
这可能吗?我怎样才能做到这一点?
最佳答案
您可以在指令的 compile
属性中实现它,因此添加:
compile:function(element,attrs){
element.find('li').append(attrs.mlParser);
}
PLNKR示例。
关于javascript - 带有动态模板的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903875/