服务的本质是一个单例对象,提供数据和对象。
两大类:
①内置服务
location scope rootScope window interval timeout等等
使用内置服务中提供的方法:
第一步 将需要用到的服务注入进来 function(
scope,
location)
第二步 调用服务中提供的方法 数据。。
案例:通过内置的$interval做一个轮播图
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="myCtrl">
<img ng-src="img/{{imgList[index]}}" alt=""/>
<h1>{{count}}</h1>
</div>
<script>
var app = angular.module('myApp', ['ng']);
app.controller('myCtrl', function ($scope,$interval) {
$scope.count = 0;
timer = $interval(function () {
$scope.count++;
if($scope.count > 20)
{
$interval.cancel(timer)
}
},500)
$scope.index = 0;
$scope.imgList = ['1.jpg','2.jpg','3.jpg']
$interval(function () {
$scope.index++;
if($scope.index > 2)
{
$scope.index = 0;
}
},1000)
});
</script>
</body>
</html>
②自定义的服务
服务的目的是为了封装业务逻辑,提高代码的复用率
自定义服务的方法:
app.factory (‘服务名称’,function(){//普通方法 return {}})
app.service(‘服务名称’,function(){//构造函数})
app.constant(‘服务名称’,{})//创建常量服务
app.value(‘服务名称’,{})//创建变量服务
通过app.factory (‘服务名称’,function(){//普通方法 return {}})创建服务
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="myCtrl">
<button ng-click="handleClick()">clickMe</button>
</div>
<script>
var app = angular.module('myApp', ['ng']);
//创建自定义服务
app.factory('$output', function () {
return {
print: function () {
console.log('func in $output is called');
}
}
})
app.controller('myCtrl', function ($scope,$output) {
$scope.handleClick = function () {
//调用自定义服务所提供的方法
$output.print();
}
});
</script>
</body>
</html>
通过app.service(‘服务名称’,function(){//构造函数})创建服务
<script>
var app = angular.module('myApp', ['ng']);
//自定义服务
app.service('$student', function () {
this.study = function () {
console.log('we are learning...');
}
this.name = "zhangSan";
})
app.controller('myCtrl',
function ($scope, $student) {
$student.study();
});
</script>
</body>
</html>
**通过app.constant(‘服务名称’,{})//创建常量服务
app.value('服务名称',{})//创建变量服务**
<script>
var app = angular.module('myApp', ['ng']);
//创建常量服务
app.constant('$Author',{name:'KKK',email:'**@163.com'})
//创建变量服务
app.value('$Config',{version:1})
app.controller('myCtrl', function ($scope,$Author,$Config) {
console.log($Author.email);
console.log($Config.version);
});
</script>
注意事项:
自定义的服务 需要用到其它服务中方法
<body>
<div ng-controller="myCtrl">
<button ng-click="start()">开始</button>
<button ng-click="stop()">结束</button>
</div>
<script>
var app = angular.module('myApp', ['ng']);
//通过service方法去创建自定义服务
app.service('$HeartBeat', function ($interval) {
this.startBeat = function () {
promise = $interval(function () {
console.log('beat...');
},1000);
}
this.stopBeat = function () {
$interval.cancel(promise);
}
})
app.controller('myCtrl', function ($scope,$HeartBeat) {
$scope.start = function () {
$HeartBeat.startBeat();
}
$scope.stop = function () {
$HeartBeat.stopBeat();
}
});
</script>