This page looks best with JavaScript enabled

Factory and Services in AngularJS

 ·  ☕ 2 min read  ·  ✍️ Adesh

factory services angularjs factory and services in angularjs

In the previous post, we discussed about Directives, Modules, Controllers  and Scopes. In this tutorial, we are going to learn about factory and services in AngularJS. 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:

http://codetalkie.com/2018/10/13/how-to-create-and-use-filters-in-angularjs/

http://codetalkie.com/2018/10/14/the-power-of-directives-in-angularjs/

Introduction to Module and Directives in AngularJS

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect