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...
https://www.programming-free.com/2013/11/angularjs-services-simple-example.html
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,
Let us now recreate our controller example for performing total price calculation using services.
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!!
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.
ReplyDeleteCustomers 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.
ReplyDeleteJava 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.
ReplyDeleteIn 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