Skip to content

Instantly share code, notes, and snippets.

@kranthilakum
Last active January 4, 2016 16:09
Show Gist options
  • Save kranthilakum/8645504 to your computer and use it in GitHub Desktop.
Save kranthilakum/8645504 to your computer and use it in GitHub Desktop.
Angular.js: service vs provide vs factory
var myApp = angular.module('myApp', []);
// a simple service
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
// a simple factory
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
// a configurable provider
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;
};
});
// configuring a provider
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
// controller
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
/*
<!-- invoke controller -->
<div ng-controller="MyCtrl">
{{hellos}}
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment