標籤:
我們在上一課做了很多基礎性的訓練,接下來,我們講一些痛點的知識點,首先,講一下如何?一個全文檢索索引功能:
<html ng-app><head> ... <script src="lib/angular/angular.js"></script> <script> function PhoneListCtrl($scope) { $scope.phones = [ {"name": "Nexus S","snippet": "Fast just got faster with Nexus S."}, {"name": "Motorola XOOM™ with Wi-Fi","snippet": "The Next, Next Generation tablet."}, {"name": "MOTOROLA XOOM™", "snippet": "The Next, Next Generation tablet."} ]; } </script></head><body ng-controller="PhoneListCtrl"> <div class="container-fluid"> <div class="row-fluid"> <div class="span2"> Search: <input ng-model="query"> </div> <div class="span10"> <ul class="phones"> <li ng-repeat="phone in phones | filter:query"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> </div> </div> </div></body></html>
上面這個代碼的功能:允許使用者輸入一個搜尋條件,立刻就能看到電話列表中的搜尋結果。
當頁面載入後,AngularJS會根據輸入框中的值,將其與資料模型中相同名字的變數($scope.query)綁定在一起,以確保兩者的同步性。
在這段代碼中,使用者在輸入框中輸入的值稱作query,會立刻作為列表迭代器(phone in phones | filter:query`)其過濾器的輸入。
使用filter過濾器:filter函數使用query的值來建立一個只包含匹配query記錄的新數組。
ngRepeat會根據filter過濾器產生的手機記錄資料數組來自動更新視圖。整個過程對於開發人員來說都是透明的。
接下來,我們將在上面的例子中添加一個新的功能:增加一個讓使用者控制手機列表顯示順序的功能
Search: <input ng-model="query">Sort by:<select ng-model="orderProp"> <option value="name">Alphabetical</option> <option value="age">Newest</option></select><ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp"> {{phone.name}} <p>{{phone.snippet}}</p> </li></ul>
我們在html中做了如下更改:
- 首先,我們增加了一個叫做
orderProp的<select>標籤,這樣我們的使用者就可以選擇我們提供的兩種排序方法。
- 然後,在
filter過濾器後面添加一個orderBy過濾器用其來處理進入迭代器的資料。orderBy過濾器以一個數組作為輸入,複製一份副本,然後把副本重排序再輸出到迭代器。
AngularJS在select元素和orderProp模型之間建立了一個雙向繫結。而且orderProp會被用作orderBy過濾器的輸入。
無論什麼時候資料模型發生了改變(比如使用者在下拉式功能表中選了不同的選項),AngularJS的資料繫結會讓視圖自動更新。沒有任何笨拙的DOM操作!
function PhoneListCtrl($scope) { $scope.phones = [ {"name": "Nexus S", "snippet": "Fast just got faster with Nexus S.", "age": 0}, {"name": "Motorola XOOM™ with Wi-Fi", "snippet": "The Next, Next Generation tablet.", "age": 1}, {"name": "MOTOROLA XOOM™", "snippet": "The Next, Next Generation tablet.", "age": 2} ]; $scope.orderProp = ‘age‘;}
當應用在瀏覽器中載入時,“Newest”在下拉式功能表中被選中。這是因為我們在控制器中我們把orderProp設定成了‘age’。所以綁定,從模型到使用者介面的方向上起了作用——即資料從模型到視圖的綁定。現在當你在下拉式功能表中選擇“Alphabetically”,資料模型會被同時更新,並且手機列表數組會被重新排序。這個時候資料繫結從另一個方向產生了作用——即資料從視圖到模型的綁定。
最後,通過一幅圖來看一下這個例子的M和V是如何分離的:
看了這個例子,大家是否覺得使用angular進行開發,是不是很方便啊。它封裝了事件綁定,DOM操作,模板解析等操作,大大的減少了開發工作單位。
加油!
AngularJS入門講解2