假設我有角度的服務並告訴我如何在不同的控制器和模塊中重複使用該服務。看到代碼採取Angular:如何在不同的控制器和模塊上重複使用服務
代碼從http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
<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>
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);
}
});
該服務已被聲明,並與應用程序模塊附接。現在告訴我,如果我需要在另一個模塊調用app1中使用相同的服務,那麼我需要在app1模塊中定義並附加相同的服務嗎?
尋找指導。
偉大的示例代碼女士......非常感謝:) – Mou