Javascript 带有动态模板的指令
假设我有一个指令,它接受一个模型并用Javascript 带有动态模板的指令,javascript,angularjs,Javascript,Angularjs,假设我有一个指令,它接受一个模型并用ng repeat打印所有模型的元素。比如: (function () { 'use strict'; angular .module('myDirective', []) .directive('myDirective', myDirective); function myDirective() { return { restrict: 'E',
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>'
};
}
})();
<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>
指令的使用方式如下:
<my-directive ml-model="vm.testModel"></my-directive>
结构相同,但是现在code
属性被称为id
,而name
属性被称为description
。由于在指令中我硬编码了如何读取模型(即,我编写了{{actor.code}}-{{actor.name}
),所以产生了巨大的问题
我会将用于模型读取的代码作为指令参数发送,并在指令的模板中使用它。比如:
(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>'
};
}
})();
<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>
这可能吗?我该怎么做呢?我稍微更改了指令代码,请看:
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>'
};
}
函数myDirective(){
返回{
限制:'E',
范围:{
mlModel:“=”,
},
链接:函数(范围、元素、属性){
scope.view=[];
scope.mlModel.forEach(函数(参与者){
scope.view.push({name:actor[Object.keys(actor)[0]],value:actor[Object.keys(actor)[1]});
});
},
模板:'- {{actor.name}}-{{actor.value}}
'
};
}
您可以在指令的compile
属性中实现它,因此添加:
compile:function(element,attrs){
element.find('li').append(attrs.mlParser);
}
示例。这将解决此问题,但在野外太脆弱:)