高效利用Angular中内置服务$http、$location等
AngularJS中为我们提供了众多的内置服务,通过这些内置服务可以轻松的实现一些常用功能。下面对Angular中常用的内置服务进行一下总结。
1.$location服务
$location服务用于返回当前页面的URL地址,示例代码如下: varapp=angular.module('myApp',[]); app.controller('customersCtrl',function($scope,$location){ $scope.myUrl=$location.absUrl(); });
这里为$scope对象定义了myUrl变量,然后利用$location服务读取到了URL地址并存储到myUrl中。
2..$http服务
$http是AngularJS中最常用的服务,它经常用于服务器的数据传输。下面的例子中服务向服务器发送请求,应用响应服务器传送过来的数据。
varapp=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=newDate().toLocaleTimeString(); $interval(function(){ $scope.theTime=newDate().toLocaleTimeString(); },1000); });
除了Angular中提供的内置服务外,我们也可以自己定义服务,利用service即可,下面是一个定义服务的基本代码框架:
app.service('hexafy',function(){ this.myFunc=function(x){ returnx.toString(16); } });
定义好服务后,我们可以像使用内置的Angular服务一样使用它:
app.controller('myCtrl',function($scope,hexafy){ $scope.hex=hexafy.myFunc(255); });
以上就是针对Angular中常用的内置服务进行的汇总,希望对大家的学习有所帮助。