AngularJS - Dependency injection in services, factories, filters etc

前端 未结 3 1937
孤城傲影
孤城傲影 2021-01-30 02:08

So I have some plugins and libraries I want to use in my angular app and (currently) I am simply referencing those functions/methods as they were intended in 99% of apps in a wa

相关标签:
3条回答
  • 2021-01-30 02:39

    While the already existing answers are correct and working, john papas angular style guide favors the use of the $inject service in Y091:

    Filter:

    app.filter('<filter', MyFilter);
    MyFilter.$inject = ['$http'];
    function MyFilter() {
      return function(data) {
      }
    }
    

    Directive:

    app.directive('<directive>', MyDirective);
    MyDirective.$inject = ['$http'];
    function MyDirective() {
      return {
        ...
      }
    }
    

    Factory:

    app.factory('<factory>', MyFactory);
    MyFactory.$inject = ['$http'];
    function MyFactory() {
      var shinyNewServiceInstance;
      return shinyNewServiceInstance;
    }
    

    Service:

    app.service('<service>', MyService);
    MyService.$inject = ['$http'];
    function MyService() {
      this.foo = foo;
      function foo(){
        ...
      }
    }
    
    0 讨论(0)
  • 2021-01-30 02:42

    For the sake of completeness, here is a service example with injection:

    app.service('<service>', ['$http', function($http) {
      this.foo = function() { ... }
    }]);
    
    0 讨论(0)
  • 2021-01-30 02:49

    Yes you can use dependency injection for filters and directives

    Ex:

    Filter:

    app.filter('<filter>', ['$http', function(http){
        return function(data){
        }
    }]);
    

    Directive:

    app.directive('<directive>', ['$http', function(http){
        return {
            ....
        }
    }]);
    

    Service:

    app.factory('<service>', ['$http', function(http) {
      var shinyNewServiceInstance;
      return shinyNewServiceInstance;
    }]);
    
    0 讨论(0)
提交回复
热议问题