AngularJS Provider


Example

Provider is available both in configuration and run phases.

The Provider recipe is syntactically defined as a custom type that implements a $get method.

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.

angular.module('app',[])
  .provider('endpointProvider', function() {
    var uri = 'n/a';
    
    this.set = function(value) {
      uri = value;
    };

    this.$get = function() {
      return {
        get: function() {
          return uri;
        }
      };
    };
  })
  .config(function(endpointProviderProvider) {
    endpointProviderProvider.set('http://some.rest.endpoint');
  })   
  .controller('MainCtrl', function(endpointProvider) {
    var vm = this;
    vm.endpoint = endpointProvider.get();
  }); 

<body ng-controller="MainCtrl as vm">
  <div>endpoint = {{::vm.endpoint }}</div>
</body>

endpoint = http://some.rest.endpoint

Without config phase result would be

endpoint = n/a