AngularJs Scope詳解及示例代碼
一、什么是Scope?
scope(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope)是一個(gè)指向應(yīng)用model的object。它也是expression(http://www.cnblogs.com/lcllao/archive/2012/09/16/2687162.html)的執(zhí)行上下文。scope被放置于一個(gè)類似應(yīng)用的DOM結(jié)構(gòu)的層次結(jié)構(gòu)中。scope可以監(jiān)測(cè)(watch,$watch)expression和傳播事件。
二、scope的特性
- scope提供$watch API(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$watch),用于監(jiān)測(cè)model的變化。
- scope提供$apply API(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$apply),在“Angular realm”(controller、server、angular event handler)之外,從系統(tǒng)到視圖傳播任何model的變化。
- scope可以在提供到被共享的model屬性的訪問(wèn)的時(shí)候,被嵌入到獨(dú)立的應(yīng)用組件中。scope通過(guò)(原型),從parent scope中繼承屬性。
- scope在expression求值之時(shí)提供上下文環(huán)境。例如,{{username}}表達(dá)式是無(wú)意義的,除非它與一個(gè)特定的定義了”username”屬性的scope一起進(jìn)行求值。
三、Scope as Data-Model(scope作為數(shù)據(jù)模型)
scope是在應(yīng)用controller與view之間的紐帶。在模版linking(http://www.cnblogs.com/lcllao/archive/2012/09/04/2669802.html)的階段,directive(http://www.cnblogs.com/lcllao/archive/2012/09/09/2677190.html)在scope中設(shè)置$watch表達(dá)式。$watch讓directive能夠得知屬性的變化,使得directive將更新后的值渲染到DOM中。
controller和directive兩者都與scope有引用,但它們兩者之間沒(méi)有(引用)(Both controllers and directives have reference to the scope, but not to each other)。這樣的安排,將controller從directive和DOM中隔離開(kāi)來(lái)。這是一個(gè)重要的地方,因?yàn)樗宑ontroller與view是隔離的,極大地提升了應(yīng)用的可測(cè)試性(greatly improves the testing story of the applications)。
<!DOCTYPE HTML> <html lang="zh-cn" ng-app> <head> <meta charset="UTF-8"> <title>data-model</title> <style type="text/css"> .ng-cloak { display: none; } </style> </head> <body class="ng-cloak"> <div ng-controller="MyController"> 你的名字: <input type="text" ng-model="username"/> <button ng-click="sayHello()">歡迎</button> <hr/> {{greeting}} </div> <script src="../angular-1.0.1.js" type="text/javascript"></script> <script type="text/javascript"> function MyController($scope) { $scope.username = "My Little Dada"; $scope.sayHello = function() { $scope.greeting = "Hello~" + $scope.username + "!"; }; } </script> </body> </html>
在上面的例子中我們可以注意到MyController以”My Little Dada”對(duì)scope中的username屬性進(jìn)行賦值。然后,scope通知input進(jìn)行賦值,將username的值預(yù)先填入input中。這展示了controller如何做才能夠?qū)懭霐?shù)據(jù)到scope中。
相似地,controller可以將行為附加在scope中,正如那個(gè)當(dāng)用戶點(diǎn)擊“歡迎”按鈕時(shí)觸發(fā)的sayHello方法一樣。sayHello方法可以讀取username屬性,也可以創(chuàng)建greeting屬性。這表明,當(dāng)它們綁定到HTML input控件時(shí),scope中的屬性會(huì)自動(dòng)更新。
邏輯上,顯示{{greeting}}涉及以下兩點(diǎn):
與定義了{(lán){greeting}}表達(dá)式的模版DOM節(jié)點(diǎn)一起檢索scope。在這個(gè)例子中,這個(gè)scope與傳遞到MyController中的scope是相同的。(我們?cè)谏院髮?huì)討論scope的層次結(jié)構(gòu))
通過(guò)之前檢索的scope,對(duì)greeting表達(dá)式進(jìn)行求值,然后將結(jié)果作為封閉DOM元素的text的值。
我們可以認(rèn)為,scope和它自己的屬性可以作為數(shù)據(jù),用于渲染視圖。scope是所有和view相關(guān)的東西單一的真相來(lái)源(The scope is the single source-of-truth for all things view related)。
從可測(cè)試性來(lái)看,controller和view的分離是值得欣喜的,因?yàn)樗试S我們?cè)跊](méi)有渲染細(xì)節(jié)的干擾下(專注于)測(cè)試行為。
it('should say hello', function() { var scopeMock = {}; var cntl = new MyController(scopeMock); // Assert that username is pre-filled expect(scopeMock.username).toEqual('World'); // Assert that we read new username and greet scopeMock.username = 'angular'; scopeMock.sayHello(); expect(scopeMock.greeting).toEqual('Hello angular!'); });
四、Scope Hierarchies(scope層次結(jié)構(gòu))
每一個(gè)angular應(yīng)用有且只有一個(gè)root scope,但可以擁有多個(gè)child scope。
應(yīng)用可以擁有多個(gè)child scope,因?yàn)橐恍ヾirective會(huì)創(chuàng)建新的child scope(參考directive文檔,查看哪些directive可創(chuàng)建新的scope,如ng-repeat)。當(dāng)新的scope被創(chuàng)建后,他們將作為一個(gè)child scope,加入到parent scope中。這樣,創(chuàng)建了一個(gè)與它們附屬的DOM相似的樹(shù)結(jié)構(gòu)。
當(dāng)angular對(duì){{username}}求值時(shí),它首先查看與當(dāng)前元素關(guān)聯(lián)的scope的username屬性。如果沒(méi)有找到對(duì)應(yīng)的屬性,它將會(huì)一直向上搜索parent scope,直到到達(dá)root scope。在javascript中,這個(gè)行為被稱為“原型繼承”,child scope典型地繼承自它們的parent。
這個(gè)例子說(shuō)明應(yīng)用中的scope(是怎樣的),屬性的原型繼承。
<!DOCTYPE HTML> <html lang="zh-cn" ng-app> <head> <meta charset="UTF-8"> <title>scope-hierarchies</title> <style type="text/css"> .ng-cloak { display: none; } .ng-scope { border: 1px dashed red; } </style> </head> <body class="ng-cloak"> <div ng-controller="MyController"> 經(jīng)理:{{employee.name}} [{{department}}] <br/> 報(bào)告: <ul> <li ng-repeat="employee in employee.reports"> {{employee.name}} [{{department}}] </li> </ul> <hr/> {{greeting}} </div> <script src="../angular-1.0.1.js" type="text/javascript"></script> <script type="text/javascript"> function MyController($scope) { $scope.department = "某部"; $scope.employee = { name:"My Little Dada", reports: [ {name:"Lcllao"}, {name:"那個(gè)誰(shuí)^o^"} ] }; } </script> </body> </html>
注意,angular自動(dòng)放置ng-scope class到與scope粘附的元素中。<style>定義在上面的例子中,通過(guò)紅色的虛線,高亮新的scope的范圍。因?yàn)閞epeater對(duì){{employee.name}}表達(dá)式求值,child scope是必須的,但取決于表達(dá)式在哪一個(gè)scope進(jìn)行求值,不同的scope有不同的結(jié)果。相似地,{{department}}的值是從root scope中原型繼承得來(lái)的,只有在那個(gè)地方有,才有department屬性的定義。
五、Retrieving Scopes from the DOM(從DOM中檢索scope)
scope作為$scope數(shù)據(jù)屬性附加到DOM中,可以被用于以調(diào)試作為目的的檢索。(在應(yīng)用中通過(guò)這個(gè)方式檢索Scope是不可能的。)附加到的DOM的root scope的位置是通過(guò)ng-app directive的位置定義的。通常ng-app是放置在<html>元素中,但它也可以放置在其他元素中,例如,只有一部分視圖需要被angular控制。
在debugger中查看scope:
1. 在瀏覽器中,對(duì)著感興趣的元素點(diǎn)擊右鍵,選擇“查看元素”。我們可以看到瀏覽器debugger高亮了我們選中的元素。
2. debugger允許我們?cè)赾onsole中通過(guò)$0變量去訪問(wèn)當(dāng)前選擇的元素。
3. 想查看關(guān)聯(lián)的scope,我們可以在console中輸入:angular.element($0).scope()
六、Scope Events Propagation(Scope事件傳播)
scope可以以類似于DOM事件的方式進(jìn)行事件傳播。事件可以被broadcast(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$broadcast)到child scope或者emit(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$emit)到parent scope中。(當(dāng)前scope如果有監(jiān)聽(tīng),也會(huì)執(zhí)行)
<!DOCTYPE HTML> <html lang="zh-cn" ng-app> <head> <meta charset="UTF-8"> <title>scope-event-propagation</title> <style type="text/css"> .ng-cloak { display: none; } </style> </head> <body class="ng-cloak"> <div ng-controller="MyController"> root scope count:{{count}} <ul> <li ng-repeat="i in [1]" ng-controller="MyController"> <button ng-click="$emit('MyEvent')">$emit("MyEvent")</button> <button ng-click="$broadcast('MyEvent')">$broadcast("MyEvent")</button> <br/> middle scope count:{{count}} <ul> <li ng-repeat="item in [1,2]" ng-controller="MyController"> Leaf scope count:{{count}} </li> </ul> </li> </ul> </div> <script src="../angular-1.0.1.js" type="text/javascript"></script> <script type="text/javascript"> function MyController($scope) { $scope.count = 0; $scope.$on("MyEvent", function() { $scope.count++; }); } </script> </body> </html>
七、Scope Life Cycle(scope生命周期)
瀏覽器正常的事件流中,當(dāng)瀏覽器接收到事件后,它會(huì)執(zhí)行一個(gè)相應(yīng)的javascript回調(diào)。一旦回調(diào)函數(shù)執(zhí)行完畢后,瀏覽器將會(huì)重繪DOM,并返回到繼續(xù)等待事件的狀態(tài)。
當(dāng)瀏覽器在angular執(zhí)行環(huán)境外調(diào)用javascript代碼時(shí),這意味著angular是不知道m(xù)odel的改變的。要正確處理model的修改,這個(gè)命令必須通過(guò)使$apply方法進(jìn)入angular執(zhí)行環(huán)境。只有在$apply方法中的model變更,才會(huì)正確地被angular統(tǒng)計(jì)。例如,一個(gè)directive監(jiān)聽(tīng)了DOM事件,例如ng-click,它必須在$apply方法中對(duì)表達(dá)式進(jìn)行求值。
在對(duì)表達(dá)式求值之后,$apply方法執(zhí)行一個(gè)$digest。在$digest階段里,scope檢查所有$watch監(jiān)聽(tīng)的表達(dá)式,將現(xiàn)在的值與舊的值作比較。臟檢查(dirty checking)是異步的。這意味著賦值語(yǔ)句(例如$scope.username=”angular”)將不會(huì)馬上導(dǎo)致一個(gè)$watch被通知,反而,$watch的通知將會(huì)延遲到$digest階段。這個(gè)延遲是必須的,因?yàn)樗讯鄠€(gè)model更新聯(lián)合到一個(gè)$watch通知中,這保證了在$watch通知的過(guò)程中,沒(méi)有其他$watch在執(zhí)行。如果一個(gè)$watch改變了model的值,那么它將會(huì)強(qiáng)制增加一個(gè)$digest周期。
1) Creation(創(chuàng)建scope)
root scope是在應(yīng)用啟動(dòng)的過(guò)程中,被$injector(http://code.angularjs.org/1.0.2/docs/api/AUTO.$injector)創(chuàng)建的。在模版linking的過(guò)程中,一些directive會(huì)創(chuàng)建新的child scope。
2) Watcher registration(注冊(cè)watcher)
在模版linking過(guò)程中,directive在scope中注冊(cè)$watch。這些watch將會(huì)被用作向DOM傳播model的值。
3) Model mutation(Model變化)
為了讓變化被正確地檢測(cè),我們需要將他們包裹在scope.$apply中。(angular API 已經(jīng)隱式地做了這部操作,所以,當(dāng)在controller中做同步的工作或者與$http或者$timeout一起做異步工作的時(shí)候,不需要額外的$apply調(diào)用)。
4) Mutation observation(變化監(jiān)測(cè))
在$apply的結(jié)尾,angular會(huì)在root scope執(zhí)行一個(gè)$digest周期,這將會(huì)傳播到所有child scope中。在$digest周期中,所有注冊(cè)了$watch的表達(dá)式或者function都會(huì)被檢查,判斷model是否發(fā)生了改變,如果改變發(fā)生了,那么對(duì)應(yīng)的$watch監(jiān)聽(tīng)器將會(huì)被調(diào)用。
5) Scope destruction(scope銷毀)
當(dāng)child scope不再是必須的時(shí)候,child scope的產(chǎn)生者有責(zé)任通過(guò)scope.$destroy() API銷毀它們(child scope)。這將會(huì)停止$digest的調(diào)用傳播傳播到child scope中,讓被child scope model使用的內(nèi)存可以被gc(garbage collector)回收。
1. Scopes and Directives
在編譯階段中,compiler依靠DOM模版匹配directive。directive通??梢苑譃閮纱箢悾?/p>
觀察型directive(Observing directives),例如dobule-curly表達(dá)式{{expression}},使用$watch方法注冊(cè)監(jiān)聽(tīng)器。無(wú)論什么時(shí)候,表達(dá)式(的值)發(fā)生改變,這類directive必須被通知,從而更新view。
監(jiān)聽(tīng)型directive(Listener directive),例如ng-click,注冊(cè)一個(gè)監(jiān)聽(tīng)器到DOM中。當(dāng)DOM的監(jiān)聽(tīng)器觸發(fā)時(shí),directive會(huì)執(zhí)行相關(guān)的表達(dá)式,并通過(guò)使用$apply方法更新視圖。
當(dāng)一個(gè)外部的事件(例如用戶動(dòng)作、timer或者XHR)被監(jiān)聽(tīng)到,相關(guān)的expression必須通過(guò)$apply方法應(yīng)用到scope中,讓所有監(jiān)聽(tīng)器能夠正確地更新。
2. Directives that Create Scopes
在大多數(shù)的情況中,directive和scope是相互影響的,但不會(huì)創(chuàng)建新的scope實(shí)例。然而,一些directive(例如ng-controller和ng-repeat)會(huì)創(chuàng)建新scope,附加child scope到對(duì)應(yīng)的DOM元素中。我們通過(guò)使用angular.element(aDomElement).scope()查看任意DOM元素的scope。
3. Controllers and Scopes
在以下的情況中,scope與controller是相互影響的:
- controller使用scope暴露controller方法到模版中(查看ng-controller(http://code.angularjs.org/1.0.2/docs/api/ng.directive:ngController))。
- controller定義方法(行為),可以改變model(scope上的屬性)。
- controller可能在model中注冊(cè)watch。這些watch會(huì)在controller行為執(zhí)行之后馬上執(zhí)行。
4. Scope $watch Performance Considerations(Scope $watch的性能考慮)
在angular中,為了檢測(cè)屬性的變化而對(duì)scope進(jìn)行臟檢測(cè)(Dirty checking),是一個(gè)普遍的操作。為此,這要求dirty checking函數(shù)必須是高效的。應(yīng)小心dirty checking函數(shù)不要做任何DOM訪問(wèn)操作,因?yàn)镈OM訪問(wèn)的速度比訪問(wèn)javascript對(duì)象屬性的速度要慢好幾個(gè)數(shù)量級(jí)。
以上就是關(guān)于AngularJS Scope 的資料整理,后續(xù)繼續(xù)補(bǔ)充相關(guān)資料,謝謝大家對(duì)本站的支持!
相關(guān)文章
通過(guò)AngularJS實(shí)現(xiàn)圖片上傳及縮略圖展示示例
本篇文章主要介紹了通過(guò)AngularJS實(shí)現(xiàn)圖片上傳及縮略圖展示,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01swiper在angularjs中使用循環(huán)輪播失效的解決方法
今天小編就為大家分享一篇swiper在angularjs中使用循環(huán)輪播失效的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09詳解如何構(gòu)建Angular項(xiàng)目目錄結(jié)構(gòu)
本篇文章主要介紹了詳解如何構(gòu)建Angular項(xiàng)目目錄結(jié)構(gòu),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07小談angular ng deploy的實(shí)現(xiàn)
這篇文章主要介紹了小談angular ng deploy的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04AngularJS的依賴注入實(shí)例分析(使用module和injector)
這篇文章主要介紹了AngularJS的依賴注入,結(jié)合實(shí)例形式分析了依賴注入的原理及使用module和injector實(shí)現(xiàn)依賴注入的步驟與操作技巧,需要的朋友可以參考下2017-01-01