AngularJS Services - Simple Example

Welcome to PART 4 of AngularJS tutorial series and we are going to see in detail, one of the important aspect of AngularJS, "Th...




Welcome to PART 4 of AngularJS tutorial series and we are going to see in detail, one of the important aspect of AngularJS, "The AngularJS Services". Before reading this article, it is recommended to look at my previous articles on AngularJS for understanding the basics.

You might have heard about this term "Services" in server side programming. Now, in a client side library like AngularJS what this means is wrapping up some functionality that can be injected in all of your controllers, directives, filters and other services as well. 

So far, in my previous articles we used controllers for everything such as gluing model and view, provide some functionality, etc. This is not the right approach to proceed. Especially when we use javascript libraries like AngularJS to do client side mvc, it is very important to follow 'separation of concerns' design principle. Every feature should have a single responsibility, for example controllers are meant for attaching model with the view via scope object and other business logic should be placed somewhere else which could then be injected/used whenever they are needed. This is the purpose why we have services in AngularJS.

Services can be created and used to implement specific tasks such as fetching data from server via AJAX calls or do some other calculations. AngularJS also provides a set of built-in services which we will explore later in this tutorial series. Let us start by creating a custom service with a simple functionality and injecting it to a controller. 

Let us take the same scenario, which I used to explain controllers in AngularJS. We used controllers to calculate the total price for the corresponding quantity entered and bind the result to view. The controller in that example looked like this,

myFirstModule.controller('myFirstController', function($scope) {
        $scope.quantity=1;
 $scope.price=10; 
 $scope.calculate = function(xval,yval) {                       
  $scope.price=xval*yval
 }
});

Let us introduce services here to perform calculate function. You can create a service in four different ways, but let us create one by registering a service with the factory method in the module api. To learn about other ways of creating service take a look at this article. To create a service, you must first define a module for your application to which this service belongs and then register it to the module using factory method of the module api as shown below,

myModule.factory('serviceName', function() {
    return { };
 });


Let us now recreate our controller example for performing total price calculation using services.

<!DOCTYPE html>
<html ng-app="myAppModule">
<head>
<title>Angular JS - programming-free.com</title>
<link href="https://dl.dropbox.com/u/96099766/DetailModalExample/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript"
        src="lib/angularjs.min.js"></script>
</head>
<body>
<div ng-controller="myAppController" style="text-align:center">
     <p style="font-size:28px;">Enter Quantity:
 <input type="text" ng-model="quantity"/></p>
 <h2>Total Cost: Rs.{{calculateval(quantity,10)}}</h2>
</div>
<script type="text/javascript">
 var myAppModule = angular.module('myAppModule', []);
    myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.calculateval = function(xval,yval) {                       
   return calculateService.calculate(xval,yval);
  }
    });
// Service 
 myAppModule.factory('calculateService', function(){
    return {
        calculate: function(xval,yval){
            return xval*yval;
        }  
    }               
    });
</script>
</body>
</html>



If you note in the above example, the functionality for calculating total price for the given quantity is performed in a service called, 'calculateService' and it is injected in controller to be called every time when value in the text box changes (quantity). Since we have bound 'quantity' as model to text input, total cost will automatically update whenever the value of 'quantity' model changes. AngularJS adds a $watch attribute behind the scenes, that keeps tracking the changes in the model and whenever the value changes all attributes using that model will be updated automatically. Here the controller depends on the service for performing calculation and does its actual job of binding calculation results to the view.

That is all for now! We have created a simple custom service and injected in a controller successfully. In my next article, I will show you how to use $http service to fire ajax calls and communicate with the server.

Please keep yourself subscribed and get notified whenever a new article is published. Thanks for reading!! 

Subscribe to GET LATEST ARTICLES!


Related

AngularJS 7979587216076714292

Post a Comment

  1. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Wondering where to go in 2020? Things to do has ranked as the best include a remote, idyllic island and the design capital.

    ReplyDelete
  2. Customers require providing mortgage agents whitby the complete names, existing addresses, previous addresses, social security numbers, company details, gross regular monthly revenue, building details, property info, as well as responsibilities details.

    ReplyDelete
  3. Java project help is available online, and it's easier to access than ever before. Whether you're working on a small project or a large one, there are experts available to guide you. Don't let a lack of knowledge hold you back - get the support you need today.

    ReplyDelete
  4. In my experience, it helps me understand how services have helped simplify the architecture of web applications. In this simple example, I can see clearly how services share data and logic across controllers in the most efficient manner possible. This concept reminds me of when Thesis Writing Help can be structured similarly where research and ideas are presented only once, but referenced in the text of the thesis.

    ReplyDelete

emo-but-icon
:noprob:
:smile:
:shy:
:trope:
:sneered:
:happy:
:escort:
:rapt:
:love:
:heart:
:angry:
:hate:
:sad:
:sigh:
:disappointed:
:cry:
:fear:
:surprise:
:unbelieve:
:shit:
:like:
:dislike:
:clap:
:cuff:
:fist:
:ok:
:file:
:link:
:place:
:contact:

SUBSCRIBE


Hot in weekRecentComments

Recent

Spring Security 4 for Spring MVC using Spring Data JPA and Spring Boot

I have been writing a series of tutorials on using Spring Security 4 in Spring MVC application starting from the basic in-memory authentication. In this post, I am writing a step by ste...

Spring Security JDBC Authentication with Password Encryption

I published a basic level tutorial on how to implement JDBC Authentication and Authorization using Spring Security last week. There are few best practices to be followed while implementing secur...

Spring Security 4 - Simple JDBC Authentication and Authorization

In one of my articles, I explained with a simple example on how to secure a Spring MVC application using Spring Security and with Spring Boot for setup. I am going to extend the same example to ...

Java String Split with Pipe Character Not Working - Solution

If you are working on Java, you might have run into this issue when you try to split a string based on a pipe character ("|"). It simply won't work. Split method in Java takes regex as an argumen...

Comments

Jason Todd:

Benefits of Investing in Corporate Stationery Design Services
Investing in Corporate Stationery Design Services offer...

Jason Todd:

Where to Find the Best Italian Lounge Furniture
Finding the best Italian lounge furniture is easier than ever, with a wide range of options available both online and in luxury furniture showrooms...

Jason Todd:

Discover the Comfort of Sofas Recliners for Sale
Sofas recliners for sale offer the perfect blend of luxury and functionality for any living space. These versatile seating solutions feature recli...

Jason Todd:

Why choose Italian living room furniture?
Italian living room furniture is a top choice for those who value quality and timeless style. Made from premium materials such as real wood, fine leather...

Jason Todd:

Why choose a waistcoat for men’s party wear?
Wearing a waistcoat for mens party wear elevates any outfit, instantly...

item