一、什麼是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; //獲取公有屬性
});
我們在改寫index.html,並刷新界面,可以發現已經獲取正確的值了
<!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的方法,我們將會在下一章進行講解。