一、什么是service
在以前的文章中,我們提到,controller是相對獨(dú)立的,也就是說,兩個(gè)controller之間,內(nèi)存是不共享的,這個(gè)controller是無法訪問其他其他controller的屬性或者方法的。但是,實(shí)際項(xiàng)目中,頁面1的controller是有可以需要頁面2的controller的。以前,我都是通過localStorage來進(jìn)行儲存,后來發(fā)來localStorage應(yīng)該是用來存儲持久化數(shù)據(jù),用來存儲臨時(shí)數(shù)據(jù),controller互相交互,官方建議通過service來進(jìn)行相互訪問。
也就是說,service是用于不同controller或者directive中用于共享數(shù)據(jù)的一種服務(wù)。
二、一個(gè)簡單的service
angular中,定義service有很多方法,如 constant,factory,service,provider,這次,我們使用service來定義一個(gè)簡單的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定義了一個(gè)服務(wù),里面有一個(gè)私有屬性,一個(gè)公有屬性,以及一個(gè)獲取私有屬性的方法。現(xiàn)在 我們就可以在controller中使用這個(gè)service
因此 我們在以前的controller中注冊這個(gè)service
app.controller('helloCtrl', function ($scope, demoService) { //注冊service $scope.author = demoService.getPriAuthor(); //獲取私有屬性});app.controller('worldCtrl', function ($scope, demoService) { $scope.author = demoService.publicAuthor; //獲取公有屬性});
我們在改寫index.html,并刷新界面,可以發(fā)現(xiàn)已經(jīng)獲取正確的值了
{{author.name}}
{{author.sex}}
{{author.name}}
{{author.sex}}
app.controller('helloCtrl', function ($scope, demoService) { $scope.author = demoService.publicAuthor; $scope.updatePublic = function () { //更新您數(shù)據(jù) demoService.publicAuthor = { name: 'fei', sex: 'female' } $scope.author = demoService.publicAuthor; }});app.controller('worldCtrl', function ($scope, demoService) { $scope.author = demoService.publicAuthor; $scope.update = function () { //同步數(shù)據(jù) $scope.author = demoService.publicAuthor; }});
我們點(diǎn)擊更新數(shù)據(jù)后,我們會更改 demoService.publicAuthor的值,我們在點(diǎn)同步數(shù)據(jù) ,會發(fā)現(xiàn) 兩個(gè)controller中的值進(jìn)行了同步。
更新
同步:
小結(jié)
我們發(fā)現(xiàn)service的作用就是用于數(shù)據(jù)共享,將同一個(gè)service中的內(nèi)容分給不同的controller,通過官方我們知道controller有很多創(chuàng)建service的方法,我們將會在下一章進(jìn)行講解。