AngularJS支持使用服務(wù)的體系結(jié)構(gòu)“關(guān)注點(diǎn)分離”的概念。服務(wù)是JavaScript函數(shù),并負(fù)責(zé)只做一個特定的任務(wù)。這也使得他們即維護(hù)和測試的單獨(dú)實(shí)體??刂破?,過濾器可以調(diào)用它們作為需求的基礎(chǔ)。服務(wù)使用AngularJS的依賴注入機(jī)制注入正常。
AngularJS提供例如許多內(nèi)在的服務(wù),如:$http, $route, $window, $location等。每個服務(wù)負(fù)責(zé)例如一個特定的任務(wù),$http是用來創(chuàng)建AJAX調(diào)用,以獲得服務(wù)器的數(shù)據(jù)。 $route用來定義路由信息等。內(nèi)置的服務(wù)總是前綴$符號。
有兩種方法來創(chuàng)建服務(wù)。
工廠
服務(wù)
使用工廠方法,我們先定義一個工廠,然后分配方法給它。
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
使用服務(wù)的方法,我們定義了一個服務(wù),然后分配方法。還注入已經(jīng)可用的服務(wù)。
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
下面的例子將展示上述所有指令。
testAngularJS.html
<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??吹浇Y(jié)果如下。