Blog>
Snippets

Angular Plugin Configuration Options

Illustrate how to pass configuration options to plugins at the time of their registration and how these configurations can be accessed within the plugin.
angular.module('myApp', [])
  .provider('myPlugin', function() {
    var config = {};

    // Configuration method for the provider
    this.configure = function(cfg) {
      config = cfg;
    };

    // Factory method that will generate the service/plugin
    this.$get = function() {
      return {
        // Plugin logic or service can access the configuration here
        doSomething: function() {
          // Use configuration in the plugin functionality
          console.log('Config value:', config.someOption);
        }
      };
    };
  });
Defines an Angular provider for 'myPlugin' that accepts configuration options via the 'configure' method. The '$get' method returns an object which represents the plugin and can access these configuration options.
angular.module('myApp')
  .config(function(myPluginProvider) {
    // Pass configuration options at registration
    myPluginProvider.configure({
      someOption: 'value'
    });
  });
Configures the 'myPluginProvider' with specific options during the module's config phase.
angular.module('myApp')
  .run(function(myPlugin) {
    // Use the plugin after configuration
    myPlugin.doSomething();
  });
Calls the 'doSomething' method from 'myPlugin' during the run phase, which will access and make use of the configuration options.