Javascript 无法将attrs.value移交给指令';s templateUrl函数
使用Angular 1.6,我定义了如下指令:Javascript 无法将attrs.value移交给指令';s templateUrl函数,javascript,angularjs,Javascript,Angularjs,使用Angular 1.6,我定义了如下指令: angular .module('myApp') .directive('lyEntity', lyEntity); function lyEntity() { return { restrict: 'E', scope: { model: '=', type: '@' }, controller: 'lyEnt
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>
但在另一个模板中使用它,如:
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>
将导致templateURLcomponents/_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"/>'
};
返回{
限制:'E',
范围:{
类型:“@”
},
链接:函数(范围、元素、属性){
$scope.templateUrl='components/_templates/'+attrs.type+'.html';
},
模板:“”
};
因此,在controller中构造模板url,将ng include
作为模板,并将src指向构造的模板url
这里有一篇关于如何使用动态模板的好文章:感谢@Chantu,我找到了一个适合我的解决方案: 指令:
angular
.module('myApp')
.directive('lyEntity', lyEntity);
function lyEntity() {
return {
restrict: 'E',
scope: {
model: '=',
type: '='
},
controller: 'lyEntityController',
controllerAs: 'vm',
bindToController: true,
template: '<ng-include src="templateUrl"/>'
};
}
并称之为:
<ly-entity model="vm.entity" type="vm.type"></ly-entity>
我必须在控制器中使用
$attrs
而不是attrs
,对吗?我解决它有点不同,并提供了一个答案-无法使用您的示例运行它,但它引导我进入正确的方向,非常感谢!