AngularJS 是最近很火紅的一套 Framework
相較於 jQuery 直接操作 DOM 物件的作法,AngularJS 是直接透過 Directives 延伸 HTML 的能力
AngularJS 有幾個比較大的特性
- 雙向資料連結(Two Way Data-Binding)
- Module
- MVC
- Dependency Injection
- Directives
先說明一下 AngularJS 的 Dependency Injection 和 Directives。
DI(Dependency Injection) 的特性就是讓你的程式不要直接相依到實體,以 AngularJS 中可以很常遇到傳入 $http,$scope等物件,但傳入順序交換沒關係,主要是因為這些都是由 AngularJS 利用 DI 特性在執行時才會依照註冊的名字傳入實體物件。
而 Directives 則是宣告式語法,在 AngularJS 中透過宣告式語法來擴充 HTML 的功能
運作流程
Angular 運作步驟
1. 最一開始會先建立一個用來作 dependency injection 的 injector
2. injector 建立一個 root scope
3. Angular 從 ngApp root 開始走訪 DOM, 把每個遇到的 directives 都 bind value
基本範例
AngularJS 使用時必須在html tag內加入ng-app,另外parser的標籤符號為兩個大括號
<!DOCTYPE HTML>
<!-- html 加上 ng-app -->
<html ng-app>
<head>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
</head>
<body>
<div class="content">
Nothing here {{'yet' + '!'}}
{{5 + 2}}
</div>
</body>
</html>
雙向資料連結Two Way Data-Binding (Model)
在 AngularJS 中,可以透過Model 完成 Two Way Data-Binding 已達到兩個物件資料同步連結的效果,通常用在input、select、textarea
<!DOCTYPE HTML>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
</head>
<body>
<input ng-model="yourName" placeholder="Input Text">
<!-- -->
<p>Hello, {{ yourName || 'Guest' }}</p>
</body>
</html>
Filter
<!-- 數字 -->
{{ 9999 | number}}
<!-- 數字逗點 -->
{{9999 + 1 | number:2}}
<!-- 貨幣 -->
{{999 * 2 | currency}}
<!-- 大寫 -->
{{'Hello' | uppercase}}
<!-- 小寫 -->
{{'Hello' | lowercase}}
<!-- JSON -->
{{obj | json}}
ngBind directive
在上述例子中,如果直接顯示在HTML上,例如:
<div>
{{ 9999 + 1}}
</div>
在 AngularJS 尚未載入之前,會直接顯示{{ 9999 + 1}},在使用者體驗上不是很好,因此可以透過ngBind解決這個問題
<!-- 預設會做HTML Escape --> <span ng-bind="9999 | number"></span> <span ng-bind="'<div>Hello</div>'"></span> <span ng-bind="'rrr'"></span>
Controller Scope
AngularJS 的 Controller 中,一個 Controller 要對應一個 Scope 來控制
<script>
function AlbumCtrl($scope) {
$scope.name = 'Johnson';
$scope.meta = [
{'upc':'000000001', 'description':'01 description'},
{'upc':'000000002', 'description':'02 description'},
{'upc':'000000003', 'description':'03 description'},
{'upc':'000000004', 'description':'04 description'},
{'upc':'000000005', 'description':'05 description'}
];
$scope.show = function() {
alert($scope.name);
};
}
</script>
<div ng-controller="AlbumCtrl">
<input ng-model="name">
<button ng-click="show()">Show Name</button>
<ul>
<!-- foreach -->
<li ng-repeat="album in meta">
<a href="#" data-upc="{{album.upc}}" ng-bind="album.description"></a>
</li>
</ul>
</div>
以上面程式為例,Scope 其實就是一個 application model ,主要用來控制Controller變數、函式等操作