服务和工厂之间的区别[重复]
Posted
技术标签:
【中文标题】服务和工厂之间的区别[重复]【英文标题】:Difference between service and factory [duplicate] 【发布时间】:2017-07-10 20:07:54 【问题描述】:我们如何将以下代码转换/更改为工厂而不是服务
在工厂和服务这两者中实施的更好方法是什么,请提出建议。 我是 AngularJs 的新手,所以请帮我解决这个问题
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body 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>
<script>
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);
);
</script>
</body>
</html>
【问题讨论】:
Service VS provider VS factory in AngularJS 检查这个链接它会清除你所有的困惑-***.com/questions/13762228/… 据我所知,这个是最好的。请参考。 ***.com/questions/23074875/… 【参考方案1】: 都是单身 它们的书写方式不同 我的人员选择是使用服务【讨论】:
【参考方案2】: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);
]);
谢谢支持
【讨论】:
以上是关于服务和工厂之间的区别[重复]的主要内容,如果未能解决你的问题,请参考以下文章
“DateTime”和“DateTimeOffset”之间的区别[重复]