Understanding and Creating AngularJS Factories

Factories are very similar to AngularJS Services, lots of people struggle to understand the difference between them, if you are one of those, I ensure you’ll clearly understand the difference after reading this tutorial in which I’ll explain the concepts behind AngularJS services and factories, after that I’ll give you a simple example of how to create a factory.

Let’s start with the services, they are basically objects containing the business logic related to an specific entity or feature of your project, for example: your application will have users, right? These users can probably perform some actions like sign up, log in, log out, etc. You could create a service to group all the user related business logic, it would have these three functions I just mentioned: signin() login() and logout(). If you want more details about services, just click on this link.

Factories are a little bit different, instead of performing actions, factories, as the name suggests, are more appropriate to generate and return objects of an specific type. To make it easier to understand let’s come back to the user example, besides the actions I mentioned above, a user has also attributes, like name, login, password, etc. We could create a factory to generate and return objects with these three attributes, it would be a users factory.

Now let’ me show you how to create factories:

var app = angular.module('factoryExample',[]);
 
app.factory('User', function(){
    return function(name, login, password){
        return {
            name : name,
            login : login,
            password : password
        }
    }
});

This is a very straightforward code, it’s the simplest factory I can create, it returns a function that creates a user object according to the parameters passed to it, now you can inject it on your controller and use it like this:

app.controller('myController', function($scope, User){
	var user1 =  new User('Kate','jhpa','urej2232js');
	console.log(user1.name);
	console.log(user1.login);
	console.log(user1.password);
});

If you run your project you should see the attributes printed on your console.

Now you must be wondering, why didn’t I put the user actions and attributes on the same object instead of creating a service and a factory for it? Well, this was just an example, you could totally do it if you prefer, there is countless ways to do it, it’s up to you to choose the most suitable for your project.

That’s it for today guys!! Leave a comment if you have any doubts or suggestions.
Till next tutorial!!

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>