Trying to learn Angular from various online sources can be quite confusing, as different people use different patterns when writing functions. Can someone please explain the .provider concept in Angular?
I have experimented with the .provider
method using four different patterns, and all of them seem to work.
Pattern A: This pattern involves placing all functions inside the return
statement.
app.provider('other', function() {
name = "Default";
return {
$get: function () {
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
}
},
setName: function (newName) {
name = newName;
}
};
});
Pattern B: In this pattern, the this
keyword is used to differentiate between the $get
method and other methods.
app.provider('other', function() {
this.name = "Default";
this.$get = function () {
var name = this.name;
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
};
};
this.setName = function(name) {
this.name = name;
};
});
Pattern C: Another pattern involves using an array [ ]
just before the function that has a return statement.
this.$get = [function () {
var name = this.name;
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
}
}];
UPDATE
Pattern D: This pattern uses .factory
followed by functionNameProvider.$get.methodName(), along with the .config
block.
app.factory('alpha', function(){
var c = ['Cadbury','Perk','Dairy Milk'];
return {
sayHello: function() { console.log('Hello, I am from Provider');},
getAllData: function() { return c; }
};
});
Then
app.config(['alphaProvider',function(alphaProvider) {
console.group('Checking Factory Pattern');
alphaProvider.$get().sayHello();
var cdata = alphaProvider.$get().getAllData();
console.log(cdata);
console.groupEnd();
}]);
I have created a JSFiddle showcasing these examples. Could you please advise on the correct/preferred way?