AngularJS 服務(Service)
AngularJS 中你可以創建自己的服務,或使用內建服務。
什麼是服務?
在 AngularJS 中,服務是一個函數或對象,可在你的 AngularJS 應用中使用。
AngularJS 內建了30 多個服務。
有個 $location 服務,它可以返回當前頁面的 URL 地址。
實例
app.controller('customersCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
注意 $location 服務是作為一個參數傳遞到 controller 中。如果要使用它,需要在 controller 中定義。
為什麼使用服務?
在很多服務中,比如 $location 服務,它可以使用 DOM 中存在的對象,類似 window.location 對象,但 window.location 對象在 AngularJS 應用中有一定的局限性。
AngularJS 會一直監控應用,處理事件變化, AngularJS 使用 $location 服務比使用 window.location 對象更好。
$location vs window.location
window.location | $location.service | |
---|---|---|
目的 | 允許對當前流覽器位置進行讀寫操作 | 允許對當前流覽器位置進行讀寫操作 |
API | 暴露一個能被讀寫的對象 | 暴露jquery風格的讀寫器 |
是否在AngularJS應用生命週期中和應用整合 | 否 | 可獲取到應用生命週期內的每一個階段,並且和$watch整合 |
是否和HTML5 API的無縫整合 | 否 | 是(對低級流覽器優雅降級) |
和應用的上下文是否相關 | 否,window.location.path返回"/docroot/actual/path" | 是,$location.path()返回"/actual/path" |
$http 服務
$http 是 AngularJS 應用中最常用的服務。 服務向伺服器發送請求,應用回應伺服器傳送過來的數據。
實例
使用 $http 服務向伺服器請求數據:
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
以上是一個非常簡單的 $http 服務實例,更多 $http 服務應用請查看 AngularJS Http 教學。
$timeout 服務
AngularJS $timeout 服務對應了 JS window.setTimeout 函數。
實例
兩秒後顯示資訊:
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
$interval 服務
AngularJS $interval 服務對應了 JS window.setInterval 函數。
實例
每一秒顯示資訊:
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
創建自定義服務
你可以創建自定義服務,鏈接到你的模組中:
創建名為hexafy 的服務:
this.myFunc = function (x) {
return x.toString(16);
}
});
要使用自定義服務,需要在定義控制器的時候獨立添加,設置依賴關係:
實例
使用自定義的的服務 hexafy 將一個數字轉換為16進制數:
$scope.hex = hexafy.myFunc(255);
});
篩檢程式中,使用自定義服務
當你創建了自定義服務,並連接到你的應用上後,你可以在控制器,指令,篩檢程式或其他服務中使用它。
在篩檢程式 myFormat 中使用服務 hexafy:
return function(x) {
return hexafy.myFunc(x);
};
}]);
在對象數組中獲取值時你可以使用篩檢程式:
創建服務 hexafy:
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>