• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

AngularJS: Service vs Factory

General · December 5, 2014

For newbies and even developers who have been working with AngularJS for a while, there is some confusion around services and factories in AngularJS. Behind the scenes they are very similar, how they are instantiated however, is another story.

The first thing to realise is that services, factories and just about everything else (except directives and controllers) are singletons. Using a factory or service is just managing a singleton. This means the same instance of a factory or service is used everywhere.

Factory

Unlike the traditional use of factories in programming, a factory is a singleton in AngularJS (crazy, I know, but lets work with what we have here). Essentially you define your functions within the file, and then return an object of properties mapped to functions.

If you are familiar with various modular Javascript patterns that were popular before front-end frameworks were popular, the below approach will look familiar to you (sans the Angular trimmings, of course).

app.factory('MyFactory', function() {
    var myFactory = {};
    var firstName = '';
    
    myFactory.setName = function(name) {
        firstName = name;
    };
    
    myFactory.getName = function() {
        return firstName;
     }
});

As you can see, you are selectively returning what we want to expose. This allows us to have private variables that cannot be accessed from within a controller. If you want to prevent certain aspects of say some code that interacts with an API being modified within a controller or directive, a factory out-of-the-box is the best choice.

Service

A service is VERY similar to a factory, in-fact it is basically the same with exception that you don’t selectively return an object of mapped functions. A service is instantiated using the “new” keyword, which means your entire service and anything mapped to “this” is returned.

app.service('MyService', function() {
    var privateVar = '';
    this.firstName = '';
    
    this.setName = function(name) {
        this.firstName = name;
    };
    
    this.getName = function() {
        return this.firstName;
     }
});

As you can see, our service is basically the same. Anything that is set on the instance of our service using “this” is public and will be exposed to any other controller or directive we inject this service into.

You might also notice we have a private variable in our service. But didn’t I say that factories are good for that kind of thing? Yes, because out-of-the-box in a factory, everything is private, you have to selectively expose things. In a service, anything on this is considered fair game and public.

Conclusion

So when should you use a factory or a service? In all seriousness, they both do the same thing. I would be more inclined to use a service for communicating with an API comprised of more than just a GET method, but rather POST, PUT, DELETE and any other transformative methods.

For reference, in a project I am currently working on. We have a custom module for overlay functionality in the app. The overlay uses a service to keep track of its state (is it opened or closed) as well as methods for setting these variables and checking their current value.

Choose what makes to you, but for the most part, a service will mostly always serve your needs. It comes down to a matter of preference, because as I pointed out earlier, they are both singletons.

Dwayne

Leave a Reply Cancel reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
basavaraj
basavaraj
7 years ago

nice article

0
basavaraj
basavaraj
7 years ago

nice article keep posting like this

0
anilkumar
anilkumar
5 years ago

Nice explanation.Thanks

0

Primary Sidebar

Popular

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • Thoughts on the Flipper Zero
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • Handling Errors with the Fetch API
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • Wild Natural Deodorant Review
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz