Created
October 18, 2013 09:08
-
-
Save PatrickJS/7038781 to your computer and use it in GitHub Desktop.
Angular.js: service vs provider vs factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var myApp = angular.module('myApp', []) | |
| //service style, probably the simplest one | |
| myApp.service('helloWorldFromService', function() { | |
| this.sayHello = function() { | |
| return "Hello, Service!" | |
| }; | |
| }); | |
| //factory style, more involved but more sophisticated | |
| myApp.factory('helloWorldFromFactory', function() { | |
| return { | |
| sayHello: function() { | |
| return "Hello, Factory!" | |
| } | |
| }; | |
| }); | |
| //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('Provider'); | |
| }); | |
| myApp.controller('MyCtrl', function($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