[英]Is it possible to inject a service into Angular 1.5 component's templateUrl property?
My directive needs a constant (MODULE_ROOT_URL) to generate the template path. 我的指令需要一个常量(MODULE_ROOT_URL)来生成模板路径。 With directive syntax, I can inject the constant to the directory factory function.
使用指令语法,我可以将常量注入目录工厂函数。 How can I convert this directive to Angular 1.5 components?
如何将此指令转换为Angular 1.5组件? Is it possible to inject a service into Angular 1.5 components?
是否可以将服务注入Angular 1.5组件?
Thanks. 谢谢。
Update: I know the service can be injected into the component controller. 更新:我知道可以将服务注入组件控制器。 But how can I inject a service for a component's templateUrl property?
但是,如何为组件的templateUrl属性注入服务?
Update2: Please see plnkr. Update2:请参阅plnkr。 I create both of directive and component version.
我创建了指令和组件版本。 The directive version works fine.
指令版本工作正常。 But the component version has error [ngTransclude:orphan]
但组件版本有错误[ngTransclude:orphan]
https://plnkr.co/edit/DMumuIpXJY6RDCX6XObz?p=preview https://plnkr.co/edit/DMumuIpXJY6RDCX6XObz?p=preview
angular.module('AbcModule')
.directive('abcDirective', ['MODULE_ROOT_URL', function (MODULE_ROOT_URL) {
return {
restrict: 'E',
templateUrl: MODULE_ROOT_URL + 'abc/abc.tpl.html'
}
}]);
templateUrl
and template
can be functions and dependencies can injected. templateUrl
和template
可以是函数,也可以注入依赖项。
angular.module('AbcModule')
.component('abcDirective', {
restrict: 'E',
templateUrl: function(MODULE_ROOT_URL) {
return MODULE_ROOT_URL + 'abc/abc.tpl.html';
}
});
Till Angular 1.4, directive
DDO has been return by function where you can have dependencies in a place. 直到Angular 1.4,
directive
DDO已经被函数返回,你可以在一个地方有依赖。 But here in Angular 1.5.3 we can have a control to add dependency inside controller
of component. 但是在Angular 1.5.3中我们可以有一个控件来在组件的
controller
中添加依赖。 You could have work around like below using ng-include
& injecting dependency inside a controller. 你可以在控制器内部使用
ng-include
和注入依赖关系,如下所示。
Markup 标记
angular.module('AbcModule')
.component('abcDirective', {
template: '<div ng-include="$ctrl.rootUrl ? $ctrl.rootUrl + \'abc/abc.tpl.html\': \'\'"></div>',
controller: function(MODULE_ROOT_URL) { //<--injected dependency here.
var self = this;
self.rootUrl = MODULE_ROOT_URL;
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.