AngularJS 服务(Service)

导语 AngularJS 服务(Service)AngularJS 中你可以创建自己的服务,或使用内建服务。什么是服务?在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。AngularJS 内建了30 多个服务。有个
AngularJS 服务(Service)
AngularJS 中你可以创建自己的服务,或使用内建服务。
什么是服务?
在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。
AngularJS 内建了30 多个服务。
有个 $location 服务,它可以返回当前页面的 URL 地址。
实例
  1. var app = angular.module('myApp', []); 
  2. app.controller('customersCtrl'function($scope, $location) { 
  3.     $scope.myUrl = $location.absUrl(); 
  4. }); 
注意 $location 服务是作为一个参数传递到 controller 中。如果要使用它,需要在 controller 中定义。
为什么使用服务?
$http 是 AngularJS 应用中最常用的服务。服务向服务器发送请求,应用响应服务器传送过来的数据。
AngularJS 会一直监控应用,处理事件变化, AngularJS 使用 $location 服务比使用 window.location 对象更好。
$http 服务
$http 是 AngularJS 应用中最常用的服务。 服务向服务器发送请求,应用响应服务器传送过来的数据。
实例
使用 $http 服务向服务器请求数据:
  1. var app = angular.module('myApp', []); 
  2. app.controller('myCtrl'function($scope, $http) { 
  3.     $http.get("welcome.htm").then(function (response) { 
  4.         $scope.myWelcome = response.data; 
  5.     }); 
  6. }); 
以上是一个非常简单的 $http 服务实例,更多 $http 服务应用请查看 AngularJS Http 教程。
$timeout 服务
AngularJS $timeout 服务对应了 JS window.setTimeout 函数。
实例
两秒后显示信息:
  1. var app = angular.module('myApp', []); 
  2. app.controller('myCtrl'function($scope, $timeout) { 
  3.     $scope.myHeader = "Hello World!"
  4.     $timeout(function () { 
  5.         $scope.myHeader = "How are you today?"
  6.     }, 2000); 
  7. }); 
$interval 服务
AngularJS $interval 服务对应了 JS window.setInterval 函数。
实例
每两秒显示信息:
  1. var app = angular.module('myApp', []); 
  2. app.controller('myCtrl'function($scope, $interval) { 
  3.     $scope.theTime = new Date().toLocaleTimeString(); 
  4.     $interval(function () { 
  5.         $scope.theTime = new Date().toLocaleTimeString(); 
  6.     }, 1000); 
  7. }); 

创建自定义服务

你可以创建自定义的访问,链接到你的模块中:
创建名为hexafy 的访问:
  1. app.service('hexafy'function() { 
  2.     this.myFunc = function (x) { 
  3.         return x.toString(16); 
  4.     } 
  5. }); 
要使用自定义的访问,需要在定义过滤器的时候独立添加:
实例
使用自定义的的服务 hexafy 将一个数字转换为16进制数:
  1. app.controller('myCtrl'function($scope, hexafy) { 
  2.     $scope.hex = hexafy.myFunc(255); 
  3. }); 
 
过滤器中,使用自定义服务
当你创建了自定义服务,并连接到你的应用上后,你可以在控制器,指令,过滤器或其他服务中使用它。
在过滤器 myFormat 中使用服务 hexafy:
  1. app.filter('myFormat',['hexify'function(hexify) { 
  2.     return function(x) { 
  3.         return hexify.myFunc(x); 
  4.     }; 
  5. }]); 
在从对象会数组中获取值时你可以使用过滤器:
创建服务 hexafy:
  1. <ul> 
  2. <li ng-repeat="x in counts">{{x | myFormat}}</li> 
  3. </ul> 

https://www.nucmc.com/ true AngularJS 服务(Service) https://www.nucmc.com/show-69-786-1.html report 4203 AngularJS 服务(Service)AngularJS 中你可以创建自己的服务,或使用内建服务。什么是服务?在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。AngularJS 内建了30 多个服务。有个
TAG:AngularJS 服务 Service
本站欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果
转载请注明: 文章转载自:BETWAY官网网 https://www.nucmc.com/show-69-786-1.html
BETWAY官网网 Copyright 2012-2014 www.nucmc.com All rights reserved.(晋ICP备13001436号-1)