Angular 服务是可以是一个函数或者对象。
(Angular的很多服务,在DOM中有对应的对象,那为什么不使用这些对象,而是要用服务呢?答:因为这些服务可以获取到Angular应用声明周期的每一个阶段,并且和$watch整合,让Angular可以监控应用,处理事件变化。普通的DOM对象则不能在Angular应用声明周期中和应用整合。)。
例如:
1.$http:用于向服务器发送请求;
$http 是
AngularJS 中的一个核心服务,用于读取远程服务器的数据。
// 简单的 GET 请求,可以改为 POST $http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { // 请求成功执行代码 、1.5废除了success与error,用then方法代替 }, function errorCallback(response) { // 请求失败执行代码 });
简写格式:$http.get('/someUrl', config).then(successCallback, errorCallback); $http.post('/someUrl', data, config).then(successCallback, errorCallback);
例子(摘自菜鸟教程):
html---
<div ng-app="myApp" ng-controller="siteCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
js--
方法1
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'http://www.runoob.com/try/angularjs/data/sites.php'
}).then(function successCallback(response) {
$scope.names = response.data.sites;
}, function errorCallback(response) {
// 请求失败执行代码
});
});
方法2
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
$http.get("http://www.runoob.com/try/angularjs/data/sites.php")
.then(function (response) {$scope.names = response.data.sites;});
});
以上代码也可以用于读取数据库数据。
2.$timeout:对应了Js中的window setTimeout,单次型延时。
3.$interval:对应了Js中的window setInterval,多次型延时。
4.自定义Angular 服务对象