Value – Factory – Service
http://jsfiddle.net/fo4qpasa/
https://docs.angularjs.org/guide/providers
https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/
http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory
var myApp = angular.module('myApp', []);
myApp.value('myValue', 123);
myApp.controller('DemoController', ['myValue', function DemoController(myValue) {
this.value= myValue;
}]);Just like with the Value recipe, the Factory recipe can create a service of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.
var myApp = angular.module('myApp', []);
myApp.value('a', 123);
myApp.factory('b',['a', function (a){
return a * 2;
}]);
myApp.controller('DemoController', ['a','b', function DemoController(a,b) {
//a = 123
//b = 246
this.value = b;
}]);
var myApp = angular.module('myApp', []);
myApp.factory('b', function (){
return new Compute();
});
myApp.controller('DemoController', ['b', function DemoController(b) {
//b = 246
this.value = b.double(123);
}]);
function Compute() {
this.double= function(a) {
return a * 2;
}
}
var myApp = angular.module('myApp', []);
myApp.service('b', Compute);
myApp.controller('DemoController', ['b', function DemoController(b) {
//b = 246
this.value = b.double(123);
}]);
function Compute() {
this.double= function(a) {
return a * 2;
}
}
var myApp = angular.module('myApp', []);
myApp.provider('b', function() {
var factor = 2;
this.setFactor= function(s) {
factor = s;
}
function Compute() {
this.double= function(a) {
return a * factor;
}
}
this.$get = function() {
return new Compute();
};
});
myApp.config(["bProvider", function(bProvider) {
bProvider.setFactor(3);
}]);
myApp.controller('DemoController', ['b', function DemoController(b) {
this.value = b.double(123);
}]);You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.
To wrap it up, let's summarize the most important points: