Angular JS 學習之服務(Service)

來源:互聯網
上載者:User

標籤:filter   interval   定義   nbsp   使用   win   src   log   header   

1.AngularJS中,可以建立自己的服務,或使用內建服務;

2.在AngularJS中,服務是一個函數或對象,可在你的AngularJS應用中使用;

AngularJS內建了30多個服務;有個$location服務,它可以返回當前頁面的URL;

var app=angular.module(‘myApp‘,[]);

app.controller(‘customersCtrl‘,function($scope,$location){

  $scope.myUrl=$location.absUrl();

});

 

3.$http是AngularJS應用中最常用的服務;服務向伺服器發送請求,應用響應伺服器傳過來的資料;

AngularJS會一直監控應用,處理事件變化,AngularJS使用$location服務比使用window。location對象更好;

var app=angular(‘myApp‘,[]);

app.controller(‘myCtrl‘,function($scope,$http){

  $http.get("Welcome.htm").then(function(response){

    $scope.myWelcome=response.data;

  });

});

 

 

4.$timeout服務:響應了JS window.setTimeout函數:

var app=angular.module(‘myApp‘,[]);

app.controller(‘myCtrl‘,function($scope,$timeout){

  $scope.myHeader="Hello World!";

  $timeout(function(){

    $scope.myHeader="How are you today?";

  },2000);

});

 

5.$interval服務:對應了JS window.setInterval函數

var app=angular.module(‘myApp‘,[]);

app.controller(‘myCtrl‘,function($scope,$interval){

  $scope.theTime=new Date().toLocaleTimeString();

  $interval(function(){

    $scope.theTime=new Date().toLocaleTimeString();

  },1000);

});

 

6.建立自訂服務:可以建立訪問自訂服務,連結到你的模組中;

app.service(‘hexafy‘,function(){

  this.myFunc=function(x){

    return x.toString(16);

  }

});

使用訪問自訂服務,需要在定義過濾器的時候獨立添加:

app.controller(‘myCtrl‘,function($scope,hexafy){

  $scope.hex=hexafy.myFunc(255);

});

 

7.過濾器中,使用自訂服務:當你建立了自訂服務,並串連到你的應用後,你可以在控制器,指令,過濾器或其他服務中使用它;

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

app.filter(‘myFormat‘,[‘hexafy‘,function(hexafy){

  return function(x){

    return hexafy.myFunc(x);

  };

}]);

 

Angular JS 學習之服務(Service)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.