AngularJS 服务(Service)+Http

AngularJS 服务(Service)

什么是服务?

在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。

AngularJS 内建了30 多个服务。

为什么使用服务?

在很多服务中,比如 $location 服务,它可以使用 DOM 中存在的对象,类似 window.location 对象,但 window.location 对象在 AngularJS 应用中有一定的局限性。

AngularJS 会一直监控应用,处理事件变化, AngularJS 使用 $location 服务比使用 window.location 对象更好。

创建自定义服务

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>255 的16进制是:</p>

<h1>{{hex}}</h1>

</div>

<p>自定义服务,用于转换16进制数:</p>

<script>
var app = angular.module('myApp', []);

app.service('hexafy', function() {
	this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});
</script>

</body>
</html>

AngularJS $http

AngularJS $http 是一个用于读取web服务器上数据的服务。

$http.get(url) 是用于读取服务器数据的函数。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.6.3/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="siteCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
	
app.controller('siteCtrl', function($scope, $http) {
	$http({
		method: 'GET',
		url: 'https://www.runoob.com/try/angularjs/data/sites.php'
	}).then(function successCallback(response) {
			$scope.names = response.data.sites;
		}, function errorCallback(response) {
			// 请求失败执行代码
	});
  
});
</script>

</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值