简体   繁体   中英

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. With directive syntax, I can inject the constant to the directory factory function. How can I convert this directive to Angular 1.5 components? Is it possible to inject a service into Angular 1.5 components?

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?

Update2: Please see plnkr. I create both of directive and component version. The directive version works fine. But the component version has error [ngTransclude:orphan]

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.

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. But here in Angular 1.5.3 we can have a control to add dependency inside controller of component. You could have work around like below using ng-include & injecting dependency inside a controller.

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;
  }
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM