AngularJs Scope詳解及示例代碼
一、什么是Scope?
scope(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope)是一個指向應(yīng)用model的object。它也是expression(http://www.cnblogs.com/lcllao/archive/2012/09/16/2687162.html)的執(zhí)行上下文。scope被放置于一個類似應(yīng)用的DOM結(jié)構(gòu)的層次結(jié)構(gòu)中。scope可以監(jiān)測(watch,$watch)expression和傳播事件。
二、scope的特性
- scope提供$watch API(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$watch),用于監(jiān)測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屬性的訪問的時候,被嵌入到獨(dú)立的應(yīng)用組件中。scope通過(原型),從parent scope中繼承屬性。
- scope在expression求值之時提供上下文環(huán)境。例如,{{username}}表達(dá)式是無意義的,除非它與一個特定的定義了”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有引用,但它們兩者之間沒有(引用)(Both controllers and directives have reference to the scope, but not to each other)。這樣的安排,將controller從directive和DOM中隔離開來。這是一個重要的地方,因為它讓controller與view是隔離的,極大地提升了應(yīng)用的可測試性(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”對scope中的username屬性進(jìn)行賦值。然后,scope通知input進(jìn)行賦值,將username的值預(yù)先填入input中。這展示了controller如何做才能夠?qū)懭霐?shù)據(jù)到scope中。
相似地,controller可以將行為附加在scope中,正如那個當(dāng)用戶點(diǎn)擊“歡迎”按鈕時觸發(fā)的sayHello方法一樣。sayHello方法可以讀取username屬性,也可以創(chuàng)建greeting屬性。這表明,當(dāng)它們綁定到HTML input控件時,scope中的屬性會自動更新。
邏輯上,顯示{{greeting}}涉及以下兩點(diǎn):
與定義了{(lán){greeting}}表達(dá)式的模版DOM節(jié)點(diǎn)一起檢索scope。在這個例子中,這個scope與傳遞到MyController中的scope是相同的。(我們在稍后將會討論scope的層次結(jié)構(gòu))
通過之前檢索的scope,對greeting表達(dá)式進(jìn)行求值,然后將結(jié)果作為封閉DOM元素的text的值。
我們可以認(rèn)為,scope和它自己的屬性可以作為數(shù)據(jù),用于渲染視圖。scope是所有和view相關(guān)的東西單一的真相來源(The scope is the single source-of-truth for all things view related)。
從可測試性來看,controller和view的分離是值得欣喜的,因為它允許我們在沒有渲染細(xì)節(jié)的干擾下(專注于)測試行為。
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))
每一個angular應(yīng)用有且只有一個root scope,但可以擁有多個child scope。
應(yīng)用可以擁有多個child scope,因為一些directive會創(chuàng)建新的child scope(參考directive文檔,查看哪些directive可創(chuàng)建新的scope,如ng-repeat)。當(dāng)新的scope被創(chuàng)建后,他們將作為一個child scope,加入到parent scope中。這樣,創(chuàng)建了一個與它們附屬的DOM相似的樹結(jié)構(gòu)。
當(dāng)angular對{{username}}求值時,它首先查看與當(dāng)前元素關(guān)聯(lián)的scope的username屬性。如果沒有找到對應(yīng)的屬性,它將會一直向上搜索parent scope,直到到達(dá)root scope。在javascript中,這個行為被稱為“原型繼承”,child scope典型地繼承自它們的parent。
這個例子說明應(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/> 報告: <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:"那個誰^o^"} ] }; } </script> </body> </html>
注意,angular自動放置ng-scope class到與scope粘附的元素中。<style>定義在上面的例子中,通過紅色的虛線,高亮新的scope的范圍。因為repeater對{{employee.name}}表達(dá)式求值,child scope是必須的,但取決于表達(dá)式在哪一個scope進(jìn)行求值,不同的scope有不同的結(jié)果。相似地,{{department}}的值是從root scope中原型繼承得來的,只有在那個地方有,才有department屬性的定義。
五、Retrieving Scopes from the DOM(從DOM中檢索scope)
scope作為$scope數(shù)據(jù)屬性附加到DOM中,可以被用于以調(diào)試作為目的的檢索。(在應(yīng)用中通過這個方式檢索Scope是不可能的。)附加到的DOM的root scope的位置是通過ng-app directive的位置定義的。通常ng-app是放置在<html>元素中,但它也可以放置在其他元素中,例如,只有一部分視圖需要被angular控制。
在debugger中查看scope:
1. 在瀏覽器中,對著感興趣的元素點(diǎn)擊右鍵,選擇“查看元素”。我們可以看到瀏覽器debugger高亮了我們選中的元素。
2. debugger允許我們在console中通過$0變量去訪問當(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)聽,也會執(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)瀏覽器接收到事件后,它會執(zhí)行一個相應(yīng)的javascript回調(diào)。一旦回調(diào)函數(shù)執(zhí)行完畢后,瀏覽器將會重繪DOM,并返回到繼續(xù)等待事件的狀態(tài)。
當(dāng)瀏覽器在angular執(zhí)行環(huán)境外調(diào)用javascript代碼時,這意味著angular是不知道m(xù)odel的改變的。要正確處理model的修改,這個命令必須通過使$apply方法進(jìn)入angular執(zhí)行環(huán)境。只有在$apply方法中的model變更,才會正確地被angular統(tǒng)計。例如,一個directive監(jiān)聽了DOM事件,例如ng-click,它必須在$apply方法中對表達(dá)式進(jìn)行求值。
在對表達(dá)式求值之后,$apply方法執(zhí)行一個$digest。在$digest階段里,scope檢查所有$watch監(jiān)聽的表達(dá)式,將現(xiàn)在的值與舊的值作比較。臟檢查(dirty checking)是異步的。這意味著賦值語句(例如$scope.username=”angular”)將不會馬上導(dǎo)致一個$watch被通知,反而,$watch的通知將會延遲到$digest階段。這個延遲是必須的,因為它把多個model更新聯(lián)合到一個$watch通知中,這保證了在$watch通知的過程中,沒有其他$watch在執(zhí)行。如果一個$watch改變了model的值,那么它將會強(qiáng)制增加一個$digest周期。
1) Creation(創(chuàng)建scope)
root scope是在應(yīng)用啟動的過程中,被$injector(http://code.angularjs.org/1.0.2/docs/api/AUTO.$injector)創(chuàng)建的。在模版linking的過程中,一些directive會創(chuàng)建新的child scope。
2) Watcher registration(注冊watcher)
在模版linking過程中,directive在scope中注冊$watch。這些watch將會被用作向DOM傳播model的值。
3) Model mutation(Model變化)
為了讓變化被正確地檢測,我們需要將他們包裹在scope.$apply中。(angular API 已經(jīng)隱式地做了這部操作,所以,當(dāng)在controller中做同步的工作或者與$http或者$timeout一起做異步工作的時候,不需要額外的$apply調(diào)用)。
4) Mutation observation(變化監(jiān)測)
在$apply的結(jié)尾,angular會在root scope執(zhí)行一個$digest周期,這將會傳播到所有child scope中。在$digest周期中,所有注冊了$watch的表達(dá)式或者function都會被檢查,判斷model是否發(fā)生了改變,如果改變發(fā)生了,那么對應(yīng)的$watch監(jiān)聽器將會被調(diào)用。
5) Scope destruction(scope銷毀)
當(dāng)child scope不再是必須的時候,child scope的產(chǎn)生者有責(zé)任通過scope.$destroy() API銷毀它們(child scope)。這將會停止$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方法注冊監(jiān)聽器。無論什么時候,表達(dá)式(的值)發(fā)生改變,這類directive必須被通知,從而更新view。
監(jiān)聽型directive(Listener directive),例如ng-click,注冊一個監(jiān)聽器到DOM中。當(dāng)DOM的監(jiān)聽器觸發(fā)時,directive會執(zhí)行相關(guān)的表達(dá)式,并通過使用$apply方法更新視圖。
當(dāng)一個外部的事件(例如用戶動作、timer或者XHR)被監(jiān)聽到,相關(guān)的expression必須通過$apply方法應(yīng)用到scope中,讓所有監(jiān)聽器能夠正確地更新。
2. Directives that Create Scopes
在大多數(shù)的情況中,directive和scope是相互影響的,但不會創(chuàng)建新的scope實例。然而,一些directive(例如ng-controller和ng-repeat)會創(chuàng)建新scope,附加child scope到對應(yīng)的DOM元素中。我們通過使用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中注冊watch。這些watch會在controller行為執(zhí)行之后馬上執(zhí)行。
4. Scope $watch Performance Considerations(Scope $watch的性能考慮)
在angular中,為了檢測屬性的變化而對scope進(jìn)行臟檢測(Dirty checking),是一個普遍的操作。為此,這要求dirty checking函數(shù)必須是高效的。應(yīng)小心dirty checking函數(shù)不要做任何DOM訪問操作,因為DOM訪問的速度比訪問javascript對象屬性的速度要慢好幾個數(shù)量級。
以上就是關(guān)于AngularJS Scope 的資料整理,后續(xù)繼續(xù)補(bǔ)充相關(guān)資料,謝謝大家對本站的支持!
相關(guān)文章
通過AngularJS實現(xiàn)圖片上傳及縮略圖展示示例
本篇文章主要介紹了通過AngularJS實現(xiàn)圖片上傳及縮略圖展示,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01swiper在angularjs中使用循環(huán)輪播失效的解決方法
今天小編就為大家分享一篇swiper在angularjs中使用循環(huán)輪播失效的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09詳解如何構(gòu)建Angular項目目錄結(jié)構(gòu)
本篇文章主要介紹了詳解如何構(gòu)建Angular項目目錄結(jié)構(gòu),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07AngularJS的依賴注入實例分析(使用module和injector)
這篇文章主要介紹了AngularJS的依賴注入,結(jié)合實例形式分析了依賴注入的原理及使用module和injector實現(xiàn)依賴注入的步驟與操作技巧,需要的朋友可以參考下2017-01-01