假设我有角度服务并告诉我如何在不同的控制器和模块中重用该服务。看到代码
代码来自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);
}
});
该服务已声明并附加了app模块。现在告诉我,如果我需要在另一个模块调用app1中使用相同的服务,那么我是否需要在app1模块中定义并附加相同的服务?
寻找指导。
答案 0 :(得分:3)
如果您想在同一模块中使用不同控制器的相同服务,您可以这样做。
但是,如果要在不同的模块中使用相同的服务,则需要将注册服务的模块包含在要重用服务的模块中。事实上,将服务放在某种可重用模块中可能更好:
var reusableModule = angular.module('reusable', []);
reusableModule.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 };
});
reusableModule.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)); };
});
//now use the reusable module in your app module
var app = angular.module('app', ['reusable']);
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相同:
var app1 = angular.module('app1', ['reusable']);
答案 1 :(得分:1)
您需要引用该应用程序&#39;来自&#39; app1&#39;的模块然后像在控制器和CalculatorService中一样注入它。
var app1 = angular.module('app1', ['app']);
app1.controller('App1Controller', function ($scope, MathService, CalculatorService) {
});