Javascript 如何在现有服务的基础上创建工厂
我正在学习angularjs,阅读有关服务和工厂的文章。这方面提供的一个例子是 在阅读本文时,我试图将服务转换为factory,这是指向的链接。但它仍然没有像预期的那样工作,我不确定我做错了什么 HTMLJavascript 如何在现有服务的基础上创建工厂,javascript,jquery,angularjs,service,factory,Javascript,Jquery,Angularjs,Service,Factory,我正在学习angularjs,阅读有关服务和工厂的文章。这方面提供的一个例子是 在阅读本文时,我试图将服务转换为factory,这是指向的链接。但它仍然没有像预期的那样工作,我不确定我做错了什么 HTML <div ng-app="app"> <div ng-controller="CalculatorController"> Enter a number: <input type="number" ng-mo
<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>
出于某种原因,你抱怨它不能实例化“应用”模块,所以一切都失败了 无论如何,下面是一个工作示例的提琴: 请注意,您不需要调用
CalculatorService.calcFactory.cube
,而是调用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);
}
});
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);
}
});