Wednesday, February 18, 2015

Angularjs - Service, Factory

var module = angular.module('myApp',[]);
module.service('userService', function(){
this.users = ['J','K','L'];
this.method1 = function(){};
this.method2 = function(){};
});

module.factory('userService',function(){
var fac = {};
fac.users = ['J', 'K','L'];
fac.method1 = function(){};
fac.method2 = function(){};
return fac;
});

Sample: Calculator app
1. MathService: includes 4 methods: add, subtract, multiply and divide
2. Calculator Service: square and cube
3. CalculatorController: handle user interactions

[html]
<div ng-app="app">
     <div ng-controller="CalculatorController">
     Enter a number:
     <input ng-model="number" type="number">
     <button ng-click="doSquare()">X<sup>2</sup></button>
     <button ng-click="doCube()">X<sup>3</sup></button>
     <div>Answer:{{answer}}</div>
     </div>
</div>

[js]
var app = angular.module('app',[]);
app.service('MathService',function(){
    this.add = function(a,b){return a+b};
    this.subtract = function(a,b){return a-b};
    this.multiply = function(a,b){return a*b};
    this.divide = function(a,b){return a/b};
});

app.service('CalculatorService', function(MathService){
       this.square = function(a) {return MathService.multiply(a,a);};
       this.cube = function(a) {return MathService.multiply(a, MathService.multiply(a,a));};
});

app.controller('CalculatorController', function($scope, CalculatorService){
$scope.doSquare = function(){
    $scope.answer = CalculatorService.square($scope.number);
} ;

 $scope.doCube = function(){
     $scope.answer = CalculatorService.cube($scope.number);
}
});

/*********************************************************/
Sample2:
1. User can add new contact
2. List of contacts should be shown
3. User can delete any contact from the contact list
4. User can edit any contact from contact list
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

No comments:

Post a Comment