Can I inject a service into a directive in AngularJS?

后端 未结 3 1361
深忆病人
深忆病人 2020-11-27 09:44

I am trying to inject a service into a directive like below:

 var app = angular.module(\'app\',[]);
 app.factory(\'myData\', function(){
     return {
             


        
3条回答
  •  孤城傲影
    2020-11-27 10:46

    You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.

    template.html

    my-directive.directive.coffee

    angular.module 'my.module'
      .factory 'myDirective', ($injector) ->
        directive = 
          restrict: 'A'
          link: (scope, element, attributes) ->
            scope.apiService = $injector.get(attributes.apiService)
    

    now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data

    For example:

    scope.apiService.query((response) ->
      scope.data = response
    , (errorResponse) ->
      console.log "ERROR fetching data for service: #{attributes.apiService}"
      console.log errorResponse.data
    )
    

    I have found this technique to be very useful when making elements that interact with API endpoints especially.

提交回复
热议问题