Friday, September 12, 2014

AngularJS: How to implement Service

Here is the simple implementation for Calculator service. I have added two services in controller.js file from previous example and register it in app.js file.


controller.js

/* Define Service */
var appService = angular.module('appService',[]);
appService.service('mathService',function(){
    this.add = function(a,b){
        return a+b;
    };
    this.multiply = function(a,b){
        return a*b;
    };
});
appService.service('calculatorService', function(mathService){
    this.square = function(a){
        return mathService.multiply(a,a);
    };
});


app.js

var configModule = angular.module('configModule',[
    'ngRoute',
    'phoneDetailModule',
    'phoneListModule',
    'appFilter',
    'appService'

]);



HTML Code to invoke that service

Enter a number:
<input type="number" ng-model="number" />
<button ng-click="doSquare()">Square</button>

No comments:

Post a Comment