Skip to content

Instantly share code, notes, and snippets.

@felixzapata
Created April 15, 2015 16:18
Show Gist options
  • Save felixzapata/1c945182f8c2ba47b1a5 to your computer and use it in GitHub Desktop.
Save felixzapata/1c945182f8c2ba47b1a5 to your computer and use it in GitHub Desktop.
" Hello world " example with factory / service / provider:
// http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory
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