Reputation: 65467
I am attempting to define and use an AngularJS provider (AngularJS v 1.3.15) .
module = angular.module('myapp', []);
// Define Provider
module.provider("Notes", function() {
this.$get = function() {
return {
someData: "ABCD"
};
};
});
// Use Provider
module.config([
'NotesProvider', function(NotesProvider) {
console.log('Configuring:', NotesProvider);
console.log NotesProvider.someData
}
]);
The output from the above is:
Configuring: Object {$get: function} //I expected this to return an object with someData as one of its members
undefined //I expected "ABCD" here
All the resources I've found show the above way of defining and using providers, but I am lost on how to make this work.
What am I doing wrong?
I've tried all sorts of things, but nothing seems to work.
Upvotes: 0
Views: 68
Reputation: 14104
That's not how providers work in Angular. Take a look at the following example and everything should be clear:
module.provider("Notes", function() {
this.someData = "ABCD";
this.$get = function() {
return {
someData: "1234"
};
};
});
module.config(function(NotesProvider) {
console.log(NotesProvider.someData); // ABCD
});
module.controller('Ctrl', function(Notes) {
console.log(Notes.someData); // 1234
});
Upvotes: 1
Reputation: 2963
Angular providers are set up so that you can configure them in the configuration phase and customize what is provided when the application is running.
So in the configuration step you have, you can configure NotesProvider to behave a specific way and then use Notes when the app is running.
var module = angular.module('myapp', []);
// Define Provider
module.provider("Notes", function() {
var someData = "ABCD";
this.configureData = function(data){
someData = data;
};
this.$get = function() {
return {
someData: someData
};
};
});
// Use Provider
module.config([
'NotesProvider', function(NotesProvider) {
NotesProvider.configureData("EFGI");
console.log('Configuring:', NotesProvider);
console.log(NotesProvider.someData); // undefined because someData is on Notes not the provider
}
])
.run(['Notes', function(Notes){
console.log('Notes: ', Notes);
}]);
Here's a sample Plunker: http://plnkr.co/edit/rdIRs6ShweYCV3FxFm3N?p=preview
Upvotes: 2