Skip to content

Instantly share code, notes, and snippets.

@yanzhihong23
Created March 14, 2017 07:18
Show Gist options
  • Save yanzhihong23/45e1f51d39fe8b1f5effd60ffd687ec4 to your computer and use it in GitHub Desktop.
Save yanzhihong23/45e1f51d39fe8b1f5effd60ffd687ec4 to your computer and use it in GitHub Desktop.
AngularJS Provider/Service/Factory Examples
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() {
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