一、什么是service
在以前的文章中,我们提到,controller是相对独立的,也就是说,两个controller之间,内存是不共享的,这个controller是无法访问其他其他controller的属性或者方法的。但是,实际项目中,页面1的controller是有可以需要页面2的controller的。以前,我都是通过localStorage来进行储存,后来发来localStorage应该是用来存储持久化数据,用来存储临时数据,controller互相交互,官方建议通过service来进行相互访问。
也就是说,service是用于不同controller或者directive中用于共享数据的一种服务。
二、一个简单的service
angular中,定义service有很多方法,如 constant,factory,service,provider,这次,我们使用service来定义一个简单的service。
app.service('demoService', function () {
"use strict";
var privateAuthor = { //私有变量
name: 'jack',
sex: 'male'
}
this.publicAuthor = { //共有变量
name: 'rose',
sex: 'female'
}
this.getPriAuthor = function () { //获取私有变量
return publicAuthor;
}
});
我们用app.service定义了一个服务,里面有一个私有属性,一个公有属性,以及一个获取私有属性的方法。现在 我们就可以在controller中使用这个service
因此 我们在以前的controller中注册这个service
<pre style="font-family: 宋体; font-size: 12pt; background-color: rgb(255, 255, 255);">
app.controller('helloCtrl', function ($scope, demoService) { //注册service
$scope.author = demoService.getPriAuthor(); //获取私有属性
});
app.controller('worldCtrl', function ($scope, demoService) {
$scope.author = demoService.publicAuthor; //获取公有属性
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="Hello">
<div style="background: yellow;" ng-controller="worldCtrl">
{{author.name}}<br/>
{{author.sex}}
</div>
<div ng-controller="helloCtrl">
{{author.name}}<br/>
{{author.sex}}
</div>
</body>
<script src="bower_components/angular/angular.min.js"></script>
<script src="src/app.js"></script>
<script src="src/controller.js"></script>
<script src="src/service.js"></script>
</html>
如图:
三、更改service的值
这时候 我们在controller中更改service的值,再来看看变化。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="Hello">
<div style="background: yellow;" ng-controller="worldCtrl">
{{author.name}}<br/>
{{author.sex}}
<button ng-click="update()">同步数据</button>
</div>
<div ng-controller="helloCtrl">
{{author.name}}<br/>
{{author.sex}}
<button ng-click="updatePublic()">更新公有变量</button>
</div>
</body>
<script src="bower_components/angular/angular.min.js"></script>
<script src="src/app.js"></script>
<script src="src/controller.js"></script>
<script src="src/service.js"></script>
</html>
app.controller('helloCtrl', function ($scope, demoService) {
$scope.author = demoService.publicAuthor;
$scope.updatePublic = function () { //更新您数据
demoService.publicAuthor = {
name: 'fei',
sex: 'female'
}
$scope.author = demoService.publicAuthor;
}
});
app.controller('worldCtrl', function ($scope, demoService) {
$scope.author = demoService.publicAuthor;
$scope.update = function () { //同步数据
$scope.author = demoService.publicAuthor;
}
});
我们点击更新数据后,我们会更改 demoService.publicAuthor的值,我们在点同步数据 ,会发现 两个controller中的值进行了同步。
更新
同步:
小结
我们发现service的作用就是用于数据共享,将同一个service中的内容分给不同的controller,通过官方我们知道controller有很多创建service的方法,我们将会在下一章进行讲解。