Tuesday, June 23, 2015

AngularJS Factory

The Factory implementation in AngularJS is similar to Service, the difference is that factory allows us to define our own objects and return them to the calling controller through the factory methods.

The following example shows how to define and use a factory services 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: