使用 Angular 1.6,我定义一个指令,如下所示:
angular
.module('myApp')
.directive('lyEntity', lyEntity);
function lyEntity() {
return {
restrict: 'E',
scope: {
model: '=',
type: '@'
},
controller: 'lyEntityController',
controllerAs: 'vm',
bindToController: true,
templateUrl: function (elem, attrs) {
return 'components/_templates/' + attrs.type + '.html'
}
};
}
但是在另一个模板中使用它,如下所示:
<ly-entity model="vm.entity" type="{{vm.type}}"></ly-entity>
将生成 templateURL components/_templates/{{vm.type}}.html
如何将 vm.type
的值移交给我的 templateUrl
函数?
最佳答案
是的,它不能按照您尝试的方式完成,因为在插入属性之前调用 templateUrl
函数。实现此目的的一种方法是使用 ng-include
。
return {
restrict: 'E',
scope: {
type: '@'
},
link: function(scope, element, attrs){
$scope.templateUrl = 'components/_templates/' + attrs.type + '.html';
},
template: '<ng-include src="templateUrl"/>'
};
因此,在 Controller 中构造模板url,以ng-include
作为模板,并将src指向构造的模板url。
这是一篇关于如何拥有动态模板的好文章:https://medium.com/angularjs-meetup-south-london/angular-directives-using-a-dynamic-template-c3fb16d03c6d#.mizywdk6s
关于javascript - 无法将 attrs.value 移交给 Directive 的 templateUrl 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595026/