Factory and Services in AngularJS

In the previous post, we discussed about Directives, Modules, Controllers  and Scopes. In this second part, we would learn about these components:-

  • Factory/Service
  • Filters
  • Custom Directives

Factory/Service

In any CRUD operation, application has to communicate with the data services to fetch the data. Even though, you can write any data fetching services in the controller itself, but it is best approach to write them separately from the controllers. Controllers are meant for writing application logic and it should be thin.

So AngularJS provide us Factory & Services, which can be use to write down all api related functionality. This make these factories and services easily maintainable and reusable. All the data fetching functionality, validating business rules and other functionalities can be write down in factories and services.

There is very thin difference between factory and services. In factory, we can create object, attach methods and variables to this object and return the object to the caller function. Whereas, in service, we get the this object, all methods and variables are attached to this object and is return by service.

Let’s make it more clear by the demonstration, how to declare and use the factory and service.

AngularJS Factory sample

Create a javascript file name SampleFactory.js.

In the above code snippet, we created factory named SampleFactory, create a factory object factoryObj, and added two factory methods of add & subtract. You can put your method logic inside these methods, and finally return the factory object factoryObj.

Similarly, we will create another javascript file for service named SampleService.js.

In Order to use above created factory and service, add these 2 files SampleFactory.js and SampleService.js in your Index.html or your main root html file.

In the next step, we will inject our SampleFactory and SampleService to our controller file MyController.js file.

Summary

In this blog, we learned about AngulaJS factory and service. We learned how to create them, inject them in our controller and how to use them.

In the next blog, I will share rest of the features of Filters and Custom Directive.

Cheers!

Read more:

Adesh

Hi, I am Adesh. I am a senior software engineer having more than 12 years of software development experience. I am a full stack developer and interested in writing the technical post on programming. I am currently working in New York City area.

This Post Has 3 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close Menu
%d bloggers like this: