Now, we’ll see factories and services in detail and how to use the same in Angular’s context.
basically this is one of the features in angular which is going to encapsulate data functionality into factories and services. so, let’s suppose i have to fetch all employees data, and i need those data into multiple controllers, so in that case i don’t have to hard code the data in there, rather what i’ll prefer i’ll move the common version to either factory or service provider to fetch data for me.
The difference between them is just the way in which they create the object that goes and gets the data.
- With the factory we actually create an object inside of the factory and return it.
- With the service we just have a standard function that uses the this keyword to define function.
- With the provider there’s a $get you define and it can be used to get the object that returns the data.
however, what i like using factories more often than the other two technique, in real life app, we can have data residing in server and we can make ajax call to fetch the same. In terms of angular we use $http object to fetch the same. But, in this case, we’ll be using simple collection of employees and fetch the same.
what we’ll first do create a factory as shown below in the snapshot and then create and empty object for the same just for the initialization purpose. then with that factory object we’ll create two functions one to fetch the employees and the other one to post the employees.
Now, we are almost done we got the factory which is going to return my collection. But, my view doesn’t know about the factory but it does know about my controller, so in that context i’ll just pass my factory to that function like shown below in the snapshot.
so, you might have noticed that I have commented the Post employee logic written in there in factory. That’s basically a To Do part, let’s suppose you want to commit certain server side activity so in that case you will take an object of employee and send the same to database via ajax call. But, currently in this context that is not needed, hence to avoid the confusion I have just commented the same. so, basically post logic will remain the same where in it’s adding the new employees to in memory array. so, with this if you try the same it will give you the same output like it did give in earlier ones. sample Output shown below.
I have also attached the solution file in it’s finished form. you can download the same for future reference. So, with this I am going to wrap with this module. See you with some other module in the next section. So, till then stay tuned.
Download Link:- Angular
1,266 total views, 1 views today