Skip to content

Instantly share code, notes, and snippets.

@Kasahs
Last active December 19, 2015 10:13
Show Gist options
  • Save Kasahs/2e4cecbd69b41cb96cad to your computer and use it in GitHub Desktop.
Save Kasahs/2e4cecbd69b41cb96cad to your computer and use it in GitHub Desktop.
A simple example to show difference between them and usage style.
// @see http://stackoverflow.com/a/17944367/2317794
var myApp = angular.module('myApp', []);
//Service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
//Factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//Provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//Hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment