Difference between service and factory
本问题已经有最佳答案,请猛点这里访问。
我们如何将下面的代码转换/更改为工厂而不是服务
在工厂和服务这两个方面,最好的实施方法是什么,请建议。我刚接触安古拉基斯,所以请帮我解决这个问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </head> <body ng-app="app"> Enter a number: <input type="number" ng-model="number" /> <button ng-click="doSquare()">X2</button> <button ng-click="doCube()">X3</button> Answer: {{answer}} 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); } }); </body> </html> |
- 两个都是单人的
- 它们的书写方式不同
- 我的人事选择是使用服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | var app = angular.module('app', []); app.factory('MathService', function(){ return { multiply : function(a, b){ return a*b; } } }); app.factory('CalculateResult', ['MathService', function(MathService){ return { square : function(a){ return MathService.multiply(a,a); }, cube : function(a){ return MathService.multiply(a, MathService.multiply(a,a)); } } }]); app.controller('CalculatorController', ['CalculateResult', '$scope', function(CalculateResult, $scope){ $scope.doSquare = function(){ $scope.answer = CalculateResult.square($scope.number); }; $scope.doCube = function(){ $scope.answer = CalculateResult.cube($scope.number); } }]); |
这是答案,谢谢你的支持