高效利用Angular中內建服務$http、$location等,高效利用angular

來源:互聯網
上載者:User

高效利用Angular中內建服務$http、$location等,高效利用angular

AngularJS中為我們提供了眾多的內建服務,通過這些內建服務可以輕鬆的實現一些常用功能。下面對Angular中常用的內建服務進行一下總結。
1.$location服務

$location服務用於返回當前頁面的URL地址,範例程式碼如下:var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $location) {  $scope.myUrl = $location.absUrl(); }); 

 這裡為$scope對象定義了myUrl變數,然後利用$location服務讀取到了URL地址並儲存到myUrl中。
2..$http服務
$http 是 AngularJS 中最常用的服務,它經常用於伺服器的資料轉送。下面的例子中服務向伺服器發送請求,應用響應伺服器傳送過來的資料。

var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) {  $http.get("welcome.htm").then(function (response) {   $scope.myWelcome = response.data;  }); }); 

3.$timeout()服務和$interval()服務
這兩個服務的功能對應的是javascript中的setTimeout()和setTimeInterval函數。一個簡單的即時更新時間例子如下:

app.controller('myCtrl', function($scope, $interval) {  $scope.theTime = new Date().toLocaleTimeString();  $interval(function () {   $scope.theTime = new Date().toLocaleTimeString();  }, 1000); }); 

 除了Angular中提供的內建服務外,我們也可以自己定義服務,利用service即可,下面是一個定義服務的基本代碼架構:

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

定義好服務後,我們可以像使用內建的Angular服務一樣使用它:

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

以上就是針對Angular中常用的內建服務進行的匯總,希望對大家的學習有所協助。

您可能感興趣的文章:
  • angularjs實現與伺服器互動分享
  • 簡介AngularJS中$http服務的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.