中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

AngularJS Service

AngularJS 中的服務是一個函數(shù)或對象。

AngularJS 中你可以創(chuàng)建自己的服務,或使用內(nèi)建服務。


什么是服務?

在 AngularJS 中,服務是一個函數(shù)或對象,可在你的 AngularJS 應用中使用。

AngularJS 內(nèi)建了30 多個服務。

有個 $location 服務,它可以返回當前頁面的 URL 地址。

實例

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
??? $scope.myUrl = $location.absUrl();
});

運行代碼 ?

注意 $location 服務是作為一個參數(shù)傳遞到 controller 中。如果要使用它,需要在 controller 中定義。


為什么使用服務?

在很多服務中,比如 $location 服務,它可以使用 DOM 中存在的對象,類似 window.location 對象,但 window.location 對象在 AngularJS 應用中有一定的局限性。

AngularJS 會一直監(jiān)控應用,處理事件變化, AngularJS 使用 $location 服務比使用 window.location 對象更好。

$location vs window.location

? window.location $location.service
目的 允許對當前瀏覽器位置進行讀寫操作 允許對當前瀏覽器位置進行讀寫操作
API 暴露一個能被讀寫的對象 暴露jquery風格的讀寫器
是否在AngularJS應用生命周期中和應用整合 可獲取到應用生命周期內(nèi)的每一個階段,并且和$watch整合
是否和HTML5 API的無縫整合 是(對低級瀏覽器優(yōu)雅降級)
和應用的上下文是否相關 否,window.location.path返回"/docroot/actual/path" 是,$location.path()返回"/actual/path"

$http 服務

$http 是 AngularJS 應用中最常用的服務。 服務向服務器發(fā)送請求,應用響應服務器傳送過來的數(shù)據(jù)。

實例

使用 $http 服務向服務器請求數(shù)據(jù):

var app = angular.module('myApp', []);
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 函數(shù)。

實例

兩秒后顯示信息:

var app = angular.module('myApp', []);
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 函數(shù)。

實例

每一秒顯示信息:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
??? $scope.theTime = new Date().toLocaleTimeString();
??? $interval(function () {
??????? $scope.theTime = new Date().toLocaleTimeString();
??? }, 1000);
});

運行代碼 ?

創(chuàng)建自定義服務

你可以創(chuàng)建自定義服務,鏈接到你的模塊中:

創(chuàng)建名為hexafy 的服務:

app.service('hexafy', function() {
??? this.myFunc = function (x) {
??????? return x.toString(16);
??? }
});

要使用自定義服務,需要在定義控制器的時候獨立添加,設置依賴關系:

實例

使用自定義的的服務 hexafy 將一個數(shù)字轉換為16進制數(shù):

app.controller('myCtrl', function($scope, hexafy) {
??? $scope.hex = hexafy.myFunc(255);
});

運行代碼 ?

過濾器中,使用自定義服務

當你創(chuàng)建了自定義服務,并連接到你的應用上后,你可以在控制器,指令,過濾器或其他服務中使用它。

在過濾器 myFormat 中使用服務 hexafy:

app.filter('myFormat',['hexafy', function(hexafy) {
??? return function(x) {
??????? return hexafy.myFunc(x);
??? };
}]);

運行代碼 ?

在對象數(shù)組中獲取值時你可以使用過濾器:

創(chuàng)建服務 hexafy:

<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

運行代碼 ?