× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Service vs provider vs factory?

Shane Keller
Apr 19, 2015
<p>An additional clarification is that factories can create functions/primitives, while services cannot. Check out this <a href="http://jsfiddle.net/" rel="nofollow">jsFiddle</a> based on Epokk's: <a href="http://jsfiddle.net/skeller88/PxdSP/1351/" rel="nofollow">http://jsfiddle.net/skeller88/PxdSP/1351/</a>.</p> <p>The factory returns a function that can be invoked:</p> <pre><code>myApp.factory('helloWorldFromFactory', function() { return function() { return "Hello, World!"; }; }); </code></pre> <p>The factory can also return an object with a method that can be invoked:</p> <pre><code>myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!"; } }; }); </code></pre> <p>The service returns an object with a method that can be invoked:</p> <pre><code>myApp.service('helloWorldFromService', function() { this.sayHello = function() { return "Hello, World!"; }; }); </code></pre> <p>For more details, see a post I wrote on the difference: <a href="http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/" rel="nofollow">http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/15666048/Service%20vs%20provider%20vs%20factory?/23394300">Stack Overflow</a>.</p>
comments powered by Disqus