Reputation: 128
I have some doubts about providers. Can someone explain me why I cannot access from the controller the "setText" provider function? I can only access functions inside the $get block.
var myMod = angular.module('myApp', []);
myMod.controller("mainCtrl", [ "$scope","greeting", function($scope, greeting){
greetingProvider.setText("Hi, ");
}]);
myMod.provider('greeting', function() {
var text = 'Hello, ';
this.setText = function(value) {
text = value;
};
this.$get = function() {
return function(name) {
console.log(text + name);
};
};
});
myMod.config(function(greetingProvider) {
greetingProvider.setText("Howdy there, ");
});
myMod.run(function(greeting) {
greeting('Ford Prefect');
});
Thanks
Upvotes: 1
Views: 62
Reputation: 193261
Providers are accessible only in configuration phase of application life cycle. Their specific purpose is to provide a way to configure the future service, which provider should return via this.$get
method.
In your case it doesn't really feel like you need a provider, simple service (factory) would have been enough. Or your can make use of factory and add one more method set
to change text
variable, stored in closure.
Upvotes: 0
Reputation: 5542
The setText
function is only exposed on your app.config. The only thing you'll have when you access the provider within your controller is what you've included inside the $get function.
For a more detailed answer, check this article:
http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/
Upvotes: 1