高效利用Angular中内置服务

前端之家收集整理的这篇文章主要介绍了高效利用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',$http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});
3.$timeout()服务和$interval()服务

这两个服务的功能对应的是javascript中的setTimeout()和setTimeInterval函数。一个简单的实时更新时间例子如下:

app.controller('myCtrl',$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',hexafy) {
    $scope.hex = hexafy.myFunc(255);
});

猜你在找的Angularjs相关文章