一 Service和Factory
AngularJS为我们内置了一些服务,如$location、$timeout、$rootScope.很多时候,我们需要自己定制的服务,AngularJS为我们提供了Service和Factory。
Service和Factory的区别:
- Service:AngularJS会使用new来初始化对象。
- Factory:使用Factory会直接获得对象。
1 Service代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/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', []);
//自定义一个服务hexafy
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
//使用自定义的的服务 hexafy 将一个数字转换为16进制数
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>
</body>
2 运行结果:
二 http操作
1 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/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>
2 运行结果
3 使用格式
// 简单的 GET 请求,可以改为 POST
$http({
method: 'GET',
url: '/someUrl'}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码});
三 参考
https://www.runoob.com/angularjs/angularjs-tutorial.html