AngularJS Services – Application Business Logic

Application Business Logic – Intro

As your application gets bigger you’ll see that you have several controllers, and every one of them controls a different part of your application. The most common usage of controllers is to communicate between the view side and the data/logic side of the application. It is a common mistake to want to put all your logic in the controller. In general, writing your logic in the controller is not recommended since the controller is better used for merging the data and the view.
The AngularJS developers thought about this, and created the AngularJS services for this task.

AngularJS logo


Simple Usage Example

Lets say you have an application with 2 tabs and 2 controllers; EmployeeController, and WorkordersController and these two controllers share some of the same features. For example: in EmployeeController you can show the employee work orders that are assigned to him, and in WorkOrdersController you can show the total work orders that are currently open.
Even if you don’t know what the tabs look like, they probably share the same data structure. Also, you may need to manipulate the data in both tabs in a similar, or exact manner.

To handle such a use case it is recommended to utilize AngularJS Services, and avoid writing the business logic in the controller, as you’ll probably end up duplicating the same code in both controllers.

To implement a solution for the above example, create a service called “workOrderService” and in it implement the entire business logic of the application. When we’ll need this logic in the controller, we will call our service and use the requested function.

angular.module('angular-work-order').service('workOrderService', function($rootScope) {
    var workOrderService= {};

    workOrderService.calculateCompletedWorkOrders = function(employee, workOrders) {
        var completed = 0;
        angular.forEach(workOrders, function(value, key) {
            if (value.StatusID == 13) {
        employee.CompletedWorkOrdersPercent = completed / workOrders.length * 100;
        return employee

    return workOrderService;


Code Review

In the above example we have written a function to calculate the completed work orders.
Now we just need to call the same “service function” in both controllers to calculate the completed work orders. The benefit from this service is that we can use it everywhere in our application and the result will be the same. All we have to do is call this service when creating new a controller.
NOTE: we can now add more business logic and functionality to our service in order to enhance it.

Read more about AngularJS Services in our AngularJS Services blog series

AngularJS Service
AngularJS Service – Application Data Management
AngularJS Service – Fetching Server Data