I am still somewhat new with angular.js, but I have been working hard on making a lot of cool demos, and apps with in in my test_angular project. When first starting out I would have logic in my controllers, which is not what they are for, they should be thin. In addition I would keep writing some of my modules in my old vanilla js manner, which works of course, but I am using angular so I should do something that makes my modules angular like. One way to do this is to use a Factory, It is one of three ways to make what is called a service in angular speak.
So to get started understating factory’s and why they are awesome, lets start with a real basic and easy to understand example.
With the html I will just have a single div element with the usual ng-app directive to bootstrap the module that I will call app, and a single controller that I will call fact-control
Right off the bat there are three things that are great about this:
- My object that contains a message value to display is not stored in a controller.
- I can define my own services that can be used in controllers, and other services like that of $scope, and $http.
In the basic example I am just returning an object literal with a simple message. For a more interesting use case example I thought I might throw something together involving the use of fixer.io.
For my view I will have it display the latest exchange rates form fixer.io, or in the event it fails for some reason hard coded data in a service called Fixer.
The service will then use $http to get the latest JSON, and in the event that it fails to do so, use a hard coded object in the service in place of the latest data.
The idea here is to pull logic away from controllers, and into a place where it belongs. I also find this as a nice way to go about working with a lot of modules at once. I can make a whole bunch of services with module.factory. Some of which may stand alone, others might depend on something, you get the idea.