Defining a "Provider" for your service makes your service injectable into the config block of your app.

The formula is fairly similar to the other service, but we must ensure to define a special function, called $get(), on our returned object.

This special function tells AngularJS how to build up the properties / functions that it should inject into the config block:

Simple Provider
angular
.module('test', [])
.provider('AuthInfo', function() {
    // Define our data (similar to a service / factory)
    this.authInfo = {
      authenticated: false,
      namespace: '',
      password: '',
      saveCookie: false
    };
 
    // Now, for the special provider sauce: define our $get()
    this.$get = function() {
        var authInfo = this.authInfo;
        return {
            isAuth: function() { return authInfo.authenticated; },
            get: function() { return authInfo; },
            setAuth: function(authCookie) { authInfo = angular.fromJson(authCookie); }
        }
    };
})
.config([ '$routeProvider', 'AuthInfoProvider', function($routeProvider, authInfo) {
  // We should see the three methods that we defined above in $get()
  console.debug(authInfo);
}])
  • No labels