Tuesday, June 23, 2015

AngularJS Service

AngularJS services can be considered as re-usable utility classes / functions which are defined once and can be accessed anywhere in the application. Services enable modular and re-usability while designing complex applications in AngularJS.

The following example shows how to define and use a service in AngularJS

Service.html
<html ng-app="ServiceApp">
<body>
<div ng-controller="ServiceAppController">
<h3>{{title}}</h3>
<b>Hello Service:</b> {{HelloService}}<br/><br/>
<b>Hello Factory:</b> {{HelloFactory}}<br/><br/>
</div>
    <script src="angular.min.js"></script>
    <script src="ServiceApp.js"></script>
    <script src="Service.js"></script>
    <script src="ServiceController.js"></script>
</body>
</html>

ServiceApp.js
var app = angular.module("ServiceApp", []);

Service.js
app.service('HelloService', function () {
          this.SayHello = function(){
                   return "Hello World from Service!!!";
          }
});

app.factory('HelloFactory', function() {
    return {
        SayHello: function() {
            return "Hello World from Factory!!!";
        }
    };
});

ServiceController.js
app.controller("ServiceAppController", function($scope, HelloService, HelloFactory) {
    $scope.title = "Service and Factory in AngularJS";
    $scope.HelloService = HelloService.SayHello();
   $scope.HelloFactory = HelloFactory.SayHello();
});

Output




Search Flipkart Products:
Flipkart.com

No comments: