How should I make configurable modules in AngularJS

前端 未结 1 1497
陌清茗
陌清茗 2021-01-04 11:52

I\'ve been tinkering with AngularJS and I\'ve built up a small collection of directives and services that I would like to package into a single JS file so that I can use the

相关标签:
1条回答
  • 2021-01-04 12:08

    It sounds like you're looking for a provider.

    You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

    Here's a very basic example of a provider:

    myMod.provider('greeting', function() {
      var text = 'Hello, ';
    
      this.setText = function(value) {
        text = value;
      };
    
      this.$get = function() {
        return function(name) {
          alert(text + name);
        };
      };
    });
    

    This creates a new service, just like you might with myMod.service or myMod.factory, but provides an additional API that is available at config time—namely, a setText method. You can get access to the provider in config blocks:

    myMod.config(function(greetingProvider) {
      greetingProvider.setText("Howdy there, ");
    });
    

    Now, when we inject the greeting service, Angular will call the provider's $get method (injecting any services it asks for in its parameters) and gives you whatever it returns; in this case, $get returns a function that, when called with a name, will alert the name with whatever we've set with setText:

    myMod.run(function(greeting) {
      greeting('Ford Prefect');
    });
    
    // Alerts: "Howdy there, Ford Prefect"
    

    This is exactly how other providers, like $httpProvider and $routeProvider work.

    For more information on providers and dependency injection in general, check out this SO question on dependency injection.

    0 讨论(0)
提交回复
热议问题