How can we transform/changes below code to factory rather than service
What is the better way to implement within these two, factory and service, please suggest. I'm new to AngularJs so please help me out in this concern
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body 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>
<script>
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);
}
});
</script>
</body>
</html>
factory() is a method that takes a name and function that are injected in the same way as in service. The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not.
service() is just a Constructor, it's called with new , whereas . factory() is just a function that returns a value. Using . factory() gives us much more power and flexibility, whereas a .
The term service factory, coined by Richard B. Chase and Warren J. Erikson, represents the idea that the factory can be a source of customer service in addition to a place where products are manufactured.
The two are not the same thing, but they work together to make your Service accessible from other places. You can't get your Service without a Provider, and a Provider needs something to provide. A Service is just a term used to describe an instance of an object (which is often a TypeScript class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With