ankitdadhich ankitdadhich - 2 months ago 13
AngularJS Question

How to create factory in angular of an existing service

I am learning

angularjs
and reading articles on service and factory. One example provided on this ARTICLE is this Service Fiddle.

While reading this I am trying to convert the service into factory, this is link to My Factory Fiddle. But still it's not working as expected am not sure what I am doing wrong.

HTML

<div ng-app="app">
<div ng-controller="CalculatorController">
Enter a number:
<input type="number" ng-model="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.factory('MathService', function() {
var myFactory = {};
myFactory.add = function(a, b) { return a + b };

myFactory.subtract = function(a, b) { return a - b };

myFactory.multiply = function(a, b) { return a * b };

myFactory.divide = function(a, b) { return a / b };

retutn myFactory;
});

app.factory('CalculatorService', function(MathService){
var calcFactory = {};
calcFactory.square = function(a) { return MathService.multiply(a,a); };
calcFactory.cube = function(a) { return MathService.myFactory.multiply(a, MathService.myFactory.multiply(a,a)); };

return calcFactory;

});

app.controller('CalculatorController', function($scope, CalculatorService) {

$scope.doSquare = function() {
$scope.answer = CalculatorService.calcFactory.square($scope.number);
}

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

Answer

For some reason you fiddle complain that it can't instantiate the 'app' module, so everything fails.

anyway, here is a fiddle to a working example: https://jsfiddle.net/gom2q6bz/1/.

Please note that you don't need to call CalculatorService.calcFactory.cube but rather CalculatorService.cube;

var app = angular.module('app', []);

app.factory('MathService', function() {
  var service = {};
  service.add = function(a, b) {
    return a + b
  };

  service.subtract = function(a, b) {
    return a - b
  };

  service.multiply = function(a, b) {
    return a * b
  };

  service.divide = function(a, b) {
    return a / b
  };

  return service;
});

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

  return service;

});

app.controller('CalculatorController', function($scope, CalculatorService) {

  $scope.doSquare = function() {
    $scope.answer = CalculatorService.square($scope.number);
  }

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