Search code examples
angularjsangular-providers

How to use the `provider` and retrieve the data in `controller`


I am trying to use a provider to set and get a value in the controller. But I am not clear on how to use the provider here.

Can any one help me to use the provider with config option. I would like to know about the relationship between provider and config as well.

Here is my try, which throws error:

var app = angular.module('plunker', []);

app.value("person", {'name':"arif"});

app.constant("env", {url:"production"});

app.provider("book", function(){ //declaring provider
  var version;
  return {
    setVersion : function(value){
      version = value;
    },

    $get : function(school){
      return {
        "newVersion" : "title" + ':' + version
      }
    }
  }
});

app.config(function(newBook){ //setting a new value
    newBook.setVersion = "4.0";
});

app.controller('MainCtrl', function($scope, person, env, book) {
  $scope.name = env.url;
  $scope.value = person.name;
  $scope.version = book; //i am not getting the new value here.
});

Live Demo


Solution

  • As mentioned in my comment...

    app.config(function(bookProvider){
        bookProvider.setVersion("4.0");
    });
    

    I had to remove the missing school injection to get it to work but you should get the picture.

    Fixed ~ http://plnkr.co/edit/6Sb6rOSvA7ihvTLPTujY?p=preview

    See https://docs.angularjs.org/guide/providers#provider-recipe for more information on the provider recipe.

    See https://docs.angularjs.org/api/auto/service/$provide#provider for the .provider() docs, specifically...

    NOTE: the provider will be available under name + 'Provider' key.