1
我正在學習angularjs
並閱讀關於服務和工廠的文章。在ARTICLE上提供的一個示例是Service Fiddle。如何在現有服務的角度創建工廠
在閱讀本文時,我試圖將服務轉換爲工廠,這是鏈接到My Factory Fiddle。但仍然沒有按預期工作,我不知道我做錯了什麼。
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);
}
});