Created
December 17, 2013 12:06
-
-
Save arnabdas/8003950 to your computer and use it in GitHub Desktop.
AngularJS: Services vs. Factories vs. Providers
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
| <!DOCTYPE html> | |
| <html ng-app="app"> | |
| <head> | |
| <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script> | |
| <meta charset=utf-8 /> | |
| <title>JS Bin</title> | |
| </head> | |
| <body ng-controller="MyCtrl"> | |
| {{serviceOutput}} | |
| <br/><br/> | |
| {{factoryOutput}} | |
| <br/><br/> | |
| {{providerOutput}} | |
| <script> | |
| var app = angular.module( 'app', [] ); | |
| var MyFunc = function() { | |
| this.name = "default name"; | |
| this.$get = function() { | |
| this.name = "new name" | |
| return "Hello from MyFunc.$get(). this.name = " + this.name; | |
| }; | |
| return "Hello from MyFunc(). this.name = " + this.name; | |
| }; | |
| // returns the actual function | |
| app.service( 'myService', MyFunc ); | |
| // returns the function's return value | |
| app.factory( 'myFactory', MyFunc ); | |
| // returns the output of the function's $get function | |
| app.provider( 'myProv', MyFunc ); | |
| function MyCtrl( $scope, myService, myFactory, myProv ) { | |
| $scope.serviceOutput = "myService = " + myService; | |
| $scope.factoryOutput = "myFactory = " + myFactory; | |
| $scope.providerOutput = "myProvider = " + myProv; | |
| } | |
| </script> | |
| </body> | |
| </html> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://stackoverflow.com/questions/15666048/angular-js-service-vs-provider-vs-factory
https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/HuZsOsMvKv4J
http://jsbin.com/ohamub/1/edit