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:-
- Custom Directives
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
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
In the above code snippet, we created factory named
SampleFactory, create a factory object
factoryObj, and added two factory methods of
subtract. You can put your method logic inside these methods, and finally return the factory object
In Order to use above created factory and service, add these 2 files
SampleService.js in your Index.html or your main root html file.
In the next step, we will inject our
SampleService to our controller file MyController.js file.
In this blog, we learned about AngulaJS
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