Home  >  Article  >  Web Front-end  >  高效利用Angular中内置服务$http、$location等_AngularJS

高效利用Angular中内置服务$http、$location等_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:09:492131browse

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中常用的内置服务进行的汇总,希望对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn