2016-04-05 50 views
2

假設我有角度的服務並告訴我如何在不同的控制器和模塊中重複使用該服務。看到代碼採取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模塊中定義並附加相同的服務嗎?

尋找指導。

回答

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']); 
+0

偉大的示例代碼女士......非常感謝:) – Mou

1

您需要從「APP1引用「應用程序」模塊'然後注入它就像你在控制器和CalculatorService中一樣。

var app1 = angular.module('app1', ['app']); 

app1.controller('App1Controller', function ($scope, MathService, CalculatorService) { 

}); 
相關問題