AngularJs concepts詳解及示例代碼
原版地址:http://code.angularjs.org/1.0.2/docs/guide/concepts
繼續(xù)。。
一、總括
本文主要是angular組件(components)的概覽,并說明他們?nèi)绾喂ぷ?。列表如下?/p>
- statup - 依舊是hello world...改為Hello Kitty!
- runtime - 介紹angular的runtime
- scope - view與contorller的紐帶(神馬glue...膠)
- controller - app的行為(application behavior)
- model - app的數(shù)據(jù)
- view - 用戶所看到的東東
- directives - HTML的語法擴(kuò)展
- filters - 根據(jù)用戶的本地格式,格式化數(shù)據(jù)
- injector - 加載我們的app(依賴管理之類)
- module - 配置injector
- $ - angular的命名空間(namespace)
二、啟動(Startup)
下面描述angular是如何啟動的(參考圖表與下面的例子):
1. 瀏覽器加載HTML,將HTML標(biāo)簽轉(zhuǎn)換為DOM對象;
2. 瀏覽器加載angular.js的腳本;
3. Angular等待DOMContentLoaded事件;
4. Angular尋找ng-app這個用于指定應(yīng)用邊界范圍的directive;
5. 如果ng-app有指定module(也許是ng-app=”SomeApp”),將被用作配置$injector;
6. $injector用于創(chuàng)建$compile服務(wù)(service)以及$rootScope;
7. $compile服務(wù)用作“編譯”(有點像遍歷,然后做一點神秘的事情)DOM,并將其與對應(yīng)的$rootScope連接。
8. ng-init 這個directive在對應(yīng)的scope中創(chuàng)建name屬性并對其賦予”Kitty”值;
9. 將“{{name}}”的值插入(interpolates)到表達(dá)式中,最終顯示”Hello Kitty!”。
<!DOCTYPE html>
<html lang="zh-cn" ng-app>
<head>
<meta charset="UTF-8">
<title>Hello Kitty!</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<div ng-init="name='Kitty'">Hello {{name}}!</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
</body>
</html>
由于今晚跟別人討論一些東西,所以進(jìn)度緩慢。。。又是那句。。?,F(xiàn)在已經(jīng)是夜深了。。。Angular,廣告之后見!
==============================================
廣告完畢。。。繼續(xù)
三、Runtime

這圖表和后面的例子,描述了angular如何通過瀏覽器event-loop(所有的時間處理函數(shù),以及timer執(zhí)行的函數(shù),會排在一個queue結(jié)構(gòu)中,利用一個無限的循環(huán),不斷從queue中取出函數(shù)來執(zhí)行,這個就是event-loop。來自http://wiki.nodejs.tw/nodejs_from_scratch/javascript-yunodejs/2-1-event-loop)來進(jìn)行交互。
1. 瀏覽器event-loop等待事件到來。事件來自于用戶交互(DOM events)、timer事件(setTimeout)、network事件(服務(wù)端響應(yīng),XHR之類);
2. 事件回調(diào)函數(shù)開始執(zhí)行。這里進(jìn)入javascript上下文(context)。這回調(diào)函數(shù)可以修改DOM結(jié)構(gòu)。
3. 當(dāng)回調(diào)函數(shù)執(zhí)行完畢后,瀏覽器退出javascript context,根據(jù)DOM的改變來重繪視圖。
Angular通過創(chuàng)建自己的事件處理循環(huán)(event processing loop),修改了一般的javascript流(flow)。這將Javascript分割成傳統(tǒng)的和Angular的執(zhí)行上下文(execution context)。只要是在Angular execution context 里面執(zhí)行的操作,都擁有angular data-binding、異常處理(exception handling)、屬性監(jiān)視(property watching)等能力。我們可以通過在javascript使用$apply(),進(jìn)入Angular execution context。但要記住一點,在大多數(shù)(angular的)地方(如controllers、services),處理事件的directive會為你調(diào)用$apply。手動調(diào)用$apply的場景,一般是當(dāng)你實現(xiàn)自定義事件處理函數(shù),或者處理第三方庫的回調(diào)的時候。
1. 通過調(diào)用scope.$apply(stimulusFn)進(jìn)入angular execution context。stimulusFn就是我們想在angular execution context中執(zhí)行的函數(shù)(含scope作為參數(shù))或者angular合法的表達(dá)式。
2. Angular執(zhí)行stimulusFn,這通常會改變應(yīng)用的狀態(tài)(application state)。
3. Angular進(jìn)入$digest loop。這個loop由一個處理$evalAsync queue 和處理$watch list兩個更小的循環(huán)組成。$digest loop會在model穩(wěn)定之前保持迭代,即$evalAsync queue為空,而且$watch list沒有檢測到任何變化。
4. $evalAsync queue被用作安排必須跳出當(dāng)前堆棧幀(堆棧幀指的是在堆棧中為當(dāng)前正在運行的函數(shù)分配的區(qū)域(或空間)。傳入的參數(shù)、返回地址(當(dāng)這個函數(shù)結(jié)束后必須跳轉(zhuǎn)到該返回地址。譯注:即主調(diào)函數(shù)的斷點處)以及函數(shù)所用的內(nèi)部存儲單元(即函數(shù)存儲在堆棧上的局部變量)都在堆棧幀中。http://book.51cto.com/art/200804/70915.htm C.1.1 堆棧幀)之外,但在瀏覽器視圖繪制之前的工作。這通常是通過使用setTimeout(0)來實現(xiàn)。但setTimeout(0)這方法,會導(dǎo)致緩慢,或者在每個事件處理完畢后,瀏覽器繪制視圖時,出現(xiàn)視圖閃爍(angular有沒有去解決這個問題?如何解決?)。
5. $watch list是有可能在最近一次迭代中被修改的表達(dá)式的集合。如果(model)發(fā)生了改變,那么$watch 函數(shù)會被調(diào)用,從而達(dá)到對特定的DOM重新賦值的目標(biāo)。
6. 一旦Angular $digest loop 完成了(之前3提到的情況),離開angular和javascript的context后,瀏覽器緊跟著就會去重繪DOM,以響應(yīng)變化。
下面解釋例子“Hello Kitty”(-_-!)是如何在用戶在文本框輸入文本時實現(xiàn)數(shù)據(jù)綁定(data-binding)效果。
1. 編譯階段(compilation phase):
a) ng-model和input directive在<input>中版定keydown事件監(jiān)聽器。
b) {{name}}占位符(interpolation,不知道怎么翻譯)(表達(dá)式)設(shè)置一個$watch以便在name發(fā)生改變時有所響應(yīng)。
2. 執(zhí)行階段(runtime phase):
a) 在inut控件中按下”X”按鈕,讓瀏覽器觸發(fā)一個keydown事件;
b) input directive捕捉到文本框值的改變,然后調(diào)用$apply(“name = ‘X';”),在angular execution context中更新應(yīng)用的model。
c) Angluar將 “name = ‘X';”應(yīng)用在model中。(model發(fā)生改變)
d) $digest loop開始
e) $watch list檢測到name的值被改變了,然后再次解析{{name}}表達(dá)式,然后更新DOM。
f) Angulart退出(angular) execution context,再依次退出keydown事件以及javascript execution context;
g) 瀏覽器重繪視圖,更新字符。
<!DOCTYPE html>
<html lang="zh-cn" ng-app>
<head>
<meta charset="UTF-8">
<title>Hello Kitty!</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<input ng-model="name" class="ng-cloak"/>
<p>Hello {{name}}!</p>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
</body>
</html>
四、Scope
scope的是負(fù)責(zé)檢測model的變化,并作為表達(dá)式的執(zhí)行上下文(execution context)。Scope是在一個類似于DOM結(jié)構(gòu)的層次結(jié)構(gòu)中嵌套的(據(jù)之前了解,劃分可能跟controller有關(guān))。(詳情查看individual directive documentation,看看哪個directive會創(chuàng)建新的scope)
下面的例子展示”name”這個表達(dá)式的值是根據(jù)它依賴(所屬)的scope決定的,而且還包含了值查找的方式(類似Js的作用域鏈,自己沒有就找老爸要)。
<!DOCTYPE HTML>
<html lang="zh-cn" ng-app>
<head>
<meta charset="UTF-8">
<title>scope</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<div class="ng-cloak" ng-controller="ControllerA">
Hello {{name}}!;
</div>
<div class="ng-cloak" ng-controller="ControllerB">
Hello {{name}}!;
<div class="ng-cloak" ng-controller="ControllerC">
Hello {{name}}!;
<div class="ng-cloak" ng-controller="ControllerD">
Hello {{name}}!;
</div>
</div>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ControllerA($scope) {
$scope.name = 'Kitty';
}
function ControllerB($scope) {
$scope.name = 'Lcllao';
}
function ControllerC($scope) {
$scope.name = 'Jeffrey';
}
function ControllerD($scope) {
}
</script>
</body>
</html>
五、Controller

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app>
<head>
<meta charset="UTF-8">
<title>Controller</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<div class="ng-cloak" ng-controller="ControllerA">
Hello {{name}}!
<button ng-click="doIt()">DoIt!!</button>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ControllerA($scope) {
$scope.name = 'Kitty';
$scope.doIt = function() {
$scope.name = "Handsome";
};
}
</script>
</body>
</html>
Controller是在view背后的代碼(-_-!)。它的職責(zé)是構(gòu)建model,并通過回調(diào)函數(shù),將其(model)推送到view中。View是當(dāng)前scope到template(HTML)的映射(翻譯得有點勉強...)。Scope是指揮model到view以及向controller發(fā)送event的紐帶。
Controller與view分離是很重要的,因為:
1.Controller是寫在javascript中的。Javascript是命令式的(imperative)。命令(imperative)是描述應(yīng)用程序行為的一個好方法。Controller不應(yīng)該包含任何顯示信息(的邏輯)(DOM引用或者HTML片段)
2.View模版是寫在HTML里的。HTML是聲明式的。聲明式(的HTML)是描述UI的好方法。View不應(yīng)該包含任何行為。
3.由于Controller不知道自己需要對應(yīng)哪一個View,使得一個Controller可以(間接)使用多個View。這對于re-skinning(更換皮膚?)、其他設(shè)備特定的視圖(例如手機(jī)與桌面)還有代碼的可測性是很重要的。
六、Model

Model,可以理解為數(shù)據(jù)對象。它被用作與模版結(jié)合,以產(chǎn)生視圖。為了將model寫入到視圖中,model必須被scope所引用。與很多其他框架不一樣,angular對model沒有任何限制與要求。不需要額外添加class,也不需要通過特殊的特權(quán)方法去訪問或者改變model。Model的數(shù)據(jù)類型,可以是原始的類型(string、number……),可以是鍵值對象({a:1,b:2}),也可以是函數(shù)(function() {…})。簡要地說,angular的model只需要是一個普通的javascript對象。
七、View
view是用戶所能看到的東西。view誕生于模版。它與model結(jié)合,最終呈現(xiàn)為瀏覽器DOM。Angular采取一個對于其他很多模版系統(tǒng)來說,很不一樣的方式去呈現(xiàn)View。

其他模版引擎:很多模版引擎,是通過建立帶有特殊標(biāo)記的HTML字符串來實現(xiàn)的。通常這些模版標(biāo)記破壞了HTML的語法,這意味著不能通過一般的HTML編輯器去編輯代碼(這個嘛…)。模版字符串傳入模版引擎,與數(shù)據(jù)合并。最終生成HTML字符串。這些字符串一般通過.innerHTML的方式寫入DOM中,促使瀏覽器呈現(xiàn)模版內(nèi)容。當(dāng)數(shù)據(jù)發(fā)生改變時,這個過程需要一次又一次地重復(fù)。模版的粒度與DOM更新的粒度一致。這粒的關(guān)鍵,是模版系統(tǒng)處理字符串。
Angular:Angular模版的不同之處,在于它是基于DOM的而不是基于字符串的。模版依然需要在HTML中寫入一些字符串,但依舊是HTML(不是通過在里面嵌入模版)。瀏覽器把HTML轉(zhuǎn)換為DOM,然后DOM成為了compiler(angular的模版引擎)的輸入。Compiler查找directives,依次在model中設(shè)置watches。得出的結(jié)果,是一個一直更新的view,不需要重新拼接model與template。model成為了view的唯一數(shù)據(jù)來源(single source of truth)。
八、Directives
Directive是一個行為(例如之前文章的例子“躲貓貓”)或DOM轉(zhuǎn)換(自定義標(biāo)簽,里面包含一組DOM),將其名稱放在屬性、標(biāo)簽名、class名里面都可以觸發(fā)該directive。Directive允許你以聲明的方式擴(kuò)展HTML的標(biāo)簽。
下面的例子,還有一些疑問。就是$render如何觸發(fā)@_@
<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="myDirective">
<head>
<meta charset="UTF-8">
<title>directive</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body ng-controller="MyCtrl">
<div ng-model="content" contenteditable="true">My Little Dada</div>
<pre class="ng-cloak">modelValue = {{content}}</pre>
<button ng-click="reset()">reset(change model)</button>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
angular.module("myDirective",[])
.directive("contenteditable",function() {
return {
require:'ngModel',
link:function (scope, element, attr, ngModel) {
function setVal() {
ngModel.$setViewValue(element.text());
}
// veiw -> model
element.bind("keyup",function() {
scope.$apply(setVal);
});
// model -> view
ngModel.$render = function(val) {
console.log("render running");
element.html(val);
};
//init
setVal();
}
}
}
).controller("MyCtrl",function($scope) {
$scope.reset = function() {
$scope.content = "My Little Dada";
};
});
</script>
</body>
</html>
九、Filters
Filters 扮演一個數(shù)據(jù)轉(zhuǎn)換(格式化)的角色。通常他們是與地域有關(guān)的,不同地域也許會有不同的輸出格式。他們在追隨了Unix過濾器的精神與類似的語法:| (pipe)
<!DOCTYPE HTML>
<html lang="zh-cn" ng-app>
<head>
<meta charset="UTF-8">
<title>filter</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<div ng-init="list = ['百度B','搜狗S','360','3SB']">
數(shù)字格式化: 1233211234567 -> {{1233211234567|number}}<br/>
數(shù)組過濾,然后通過json格式輸出: <input ng-model="myFilterText" type="text"/><br/>
{{list|filter:myFilterText|json}}<br/>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
</body>
</html>
十、Modules and the Injector

Injector是一個服務(wù)定位器。每一個Angular應(yīng)用,都會有一個單獨的injector。Injector提供一個通過名稱查找對象實例的途徑。Injector會在內(nèi)部cache中保持所有對象實例,所以重復(fù)調(diào)用相同的名稱時,返回的都是同一個對象實例。如果對象不存在,那么它會請求實例工廠(instance factory)去創(chuàng)建一個新實例。
Module是一個配置injector的實例工廠的方法,被稱為”provider”。
// Create a module
var myModule = angular.module('myModule', [])
// Configure the injector
myModule.factory('serviceA', function() {
return {
// instead of {}, put your object creation here
};
});
// create an injector and configure it from 'myModule'
var $injector = angular.injector('myModule');
// retrieve an object from the injector by name
var serviceA = $injector.get('serviceA');
// always true because of instance cache
$injector.get('serviceA') === $injector.get('serviceA');//true
但是injector的真正牛X的地方在于它可以用于調(diào)用方法和”instantiate” type。這個美妙的特性是允許method和types請求他們所依賴的資源,而不是尋找他們。
// You write functions such as this one.
function doSomething(serviceA, serviceB) {
// do something here.
}
// Angular provides the injector for your application
var $injector = ...;
///////////////////////////////////////////////
// the old-school way of getting dependencies.
var serviceA = $injector.get('serviceA');
var serviceB = $injector.get('serviceB');
// now call the function
doSomething(serviceA, serviceB);
//上面是傳統(tǒng)的老方法~下面是angular說自己的牛X方法
///////////////////////////////////////////////
// the cool way of getting dependencies.
// the $injector will supply the arguments to the function automatically
$injector.invoke(doSomething); // This is how the framework calls your functions
注意,我們唯一需要寫的,就是我們的function,在function的arguments中列出方法依賴的資源即可!當(dāng)angular調(diào)用function時,他會使用”call”方法,自動填充function agruments。
留意下面的例子中是如何在constructor中列出依賴的。當(dāng)ng-controller實例化controller時,將自動提供所依賴的資源。沒有必要去創(chuàng)建、尋找、創(chuàng)建injector引用來加載依賴資源。
<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="timeExample">
<head>
<meta charset="UTF-8">
<title>injector</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
<div ng-controller="ClockCtrl" class="ng-cloak">
Current time is : {{time.now}}
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
angular.module("timeExample", []).factory("myClock", function ($timeout) {
var time = {};
(function tick() {
time.now = new Date().toString();
$timeout(tick, 1000);
})();
return time;
});
/**
*
* @param $scope
* @param myClock 這里自動插入了依賴的myClock??!
* @constructor
*/
function ClockCtrl($scope,myClock) {
$scope.time = myClock;
}
</script>
</body>
</html>
十一、Angular Namespace
為了防止名稱沖突,angular會在object的名稱中加入前綴$。請不要在代碼中使用$前綴以避免沖突。(-_-!! )
以上就是關(guān)于AngularJS concepts 的資料整理,后續(xù)繼續(xù)添加相關(guān)文章,謝謝大家對本站的支持!
- AngularJs Injecting Services Into Controllers詳解
- AngularJs Creating Services詳解及示例代碼
- AngularJs Using $location詳解及示例代碼
- AngularJs Understanding Angular Templates
- AngularJs E2E Testing 詳解
- AngularJs Understanding the Controller Component
- AngularJs Understanding the Model Component
- AngularJs Dependency Injection(DI,依賴注入)
- AngularJs Scope詳解及示例代碼
- AngularJs Modules詳解及示例代碼
- AngularJs 國際化(I18n/L10n)詳解
- AngularJs Forms詳解及簡單示例
- AngularJs expression詳解及簡單示例
- AngularJs bootstrap搭載前臺框架——js控制部分
- AngularJs Managing Service Dependencies詳解
相關(guān)文章
使用AngularJS編寫多選按鈕選中時觸發(fā)指定方法的指令代碼詳解
最近做項目時遇到了需要用到多選按鈕選中觸發(fā)事件的功能,小編試著手寫一個指令,具體實現(xiàn)代碼大家參考下本文吧2017-07-07
Angular4集成ng2-file-upload的上傳組件
本篇文章主要介紹了Angular4集成ng2-file-upload的上傳組件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
使用Angular material主題定義自己的組件庫的配色體系
這篇文章主要介紹了使用Angular material主題定義自己的組件庫的配色體系的相關(guān)知識,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
詳解angularjs 學(xué)習(xí)之 scope作用域
本篇文章主要介紹了詳解angularjs 學(xué)習(xí)之 scope作用域,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解 (上)
這篇文章主要給大家介紹了關(guān)于Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編一起來看看吧。2017-07-07

