加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS 服务(Service)

发布时间:2020-12-17 10:31:04 所属栏目:安全 来源:网络整理
导读:AngularJS 中你可以创建自己的服务,或使用内建服务。 什么是服务? 在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。 AngularJS 内建了30 多个服务。 有个 $location 服务,它可以返回当前页面的 URL 地址。 实例 var app = angula

AngularJS 中你可以创建自己的服务,或使用内建服务。

什么是服务?
在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。
AngularJS 内建了30 多个服务。
有个 $location 服务,它可以返回当前页面的 URL 地址。
实例

var app = angular.module('myApp',[]);
app.controller('customersCtrl',function($scope,$location) {
    $scope.myUrl = $location.absUrl();
});

注意 $location 服务是作为一个参数传递到 controller 中。如果要使用它,需要在 controller 中定义。

为什么使用服务?

httpAngularJSAngularJSAngularJS使 location 服务比使用 window.location 对象更好。

$http 服务

$http 是 AngularJS 应用中最常用的服务。 服务向服务器发送请求,应用响应服务器传送过来的数据。

使用 $http 服务向服务器请求数据:

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

$timeout 服务

AngularJS $timeout 服务对应了 JS window.setTimeout 函数。
实例
两秒后显示信息:

var app = angular.module('myApp',$timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    },2000);
});

$interval 服务

AngularJS $interval 服务对应了 JS window.setInterval 函数。
实例
每两秒显示信息:

var app = angular.module('myApp',$interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    },1000);
});

创建自定义服务

你可以创建访问自定义服务,链接到你的模块中:
创建名为hexafy 的访问:

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

要使用访问自定义服务,需要在定义过滤器的时候独立添加:

过滤器中,使用自定义服务

当你创建了自定义服务,并连接到你的应用上后,你可以在控制器,指令,过滤器或其他服务中使用它。
在过滤器 myFormat 中使用服务 hexafy:

app.filter('myFormat',['hexafy',function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读