簡介AngularJS中使用factory和service的方法
這篇文章主要簡單介紹了AngularJS中使用factory和service的方法,主要針對自訂工廠和服務的建立來講,需要的朋友可以參考下
AngularJS支援使用服務的體繫結構“關注點分離”的概念。服務是JavaScript函數,並負責只做一個特定的任務。這也使得他們即維護和測試的單獨實體。控制器,過濾器可以調用它們作為需求的基礎。服務使用AngularJS的依賴注入機制注入正常。
AngularJS提供例如許多內在的服務,如:$http, $route, $window, $location等。每個服務負責例如一個特定的任務,$http是用來建立AJAX調用,以獲得伺服器的資料。 $route用來定義路由資訊等。內建的服務總是首碼$符號。
有兩種方法來建立服務。
工廠
服務
使用Factory 方法
使用Factory 方法,我們先定義一個工廠,然後分配方法給它。
?
|
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>
|