简介AngularJS中使用factory和service的方法
简介AngularJS中使用factory和service的方法
AngularJS支持使用服务的体系结构“关注点分离”的概念。服务是JavaScript函数,并负责只做一个特定的任务。这也使得他们即维护和测试的单独实体。控制器,过滤器可以调用它们作为需求的基础。服务使用AngularJS的依赖注入机制注入正常。
AngularJS提供例如许多内在的服务,如:$http, $route, $window, $location等。每个服务负责例如一个特定的任务,$http是用来创建AJAX调用,以获得服务器的数据。 $route用来定义路由信息等。内置的服务总是前缀$符号。
有两种方法来创建服务。
- 工厂
- 服务
使用工厂方法
使用工厂方法,我们先定义一个工厂,然后分配方法给它。
1
2
3
4
5
6
7
8
|
var mainApp = angular.module( "mainApp" , []);
mainApp.factory( 'MathService' , function () {
var factory = {};
factory.multiply = function (a, b) {
return a * b
}
return factory;
}); |
使用服务方法
使用服务的方法,我们定义了一个服务,然后分配方法。还注入已经可用的服务。
1
2
3
4
5
|
mainApp.service( 'CalcService' , function (MathService){
this .square = function (a) {
return MathService.multiply(a,a);
}
}); |
例子
下面的例子将展示上述所有指令。
testAngularJS.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
33
34
35
36
|
<html> <head> <title>Angular JS Forms</title>
</head> <body> <h2>AngularJS Sample Application</h2>
<div ng-app= "mainApp" ng-controller= "CalcController" >
<p>Enter a number: <input type= "number" ng-model= "number" />
<button ng-click= "square()" >X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js" ></script>
<script>
var mainApp = angular.module( "mainApp" , []);
mainApp.factory( 'MathService' , function () {
var factory = {};
factory.multiply = function (a, b) {
return a * b
}
return factory;
});
mainApp.service( 'CalcService' , function (MathService){
this .square = function (a) {
return MathService.multiply(a,a);
}
});
mainApp.controller( 'CalcController' , function ($scope, CalcService) {
$scope.square = function () {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body> </html> |
结果
在Web浏览器打开textAngularJS.html。看到结果如下。