DIV CSS 佈局教程網

AngularJS 基礎指令與範例彙整
編輯:關於JavaScript     

AngularJS 是 Google 打造的前端 MVC 框架。它的核心概念是「宣告式」:你在 HTML 上標註意圖,框架負責把資料與畫面同步。以下把常用指令整理成可直接動手的小範例。

資源連結

  • 官網:https://angularjs.org/(官網有 demo,部分地區存取可能需要特殊網路環境)
  • 中文社群:https://www.angularjs.cn/,適合初學者
  • CDN 引用:https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js

使用前的三個約定

  1. 在 <head> 之前引入 angularjs。注意版本差異,本文範例使用 angular-1.0.1.min.js。
  2. 在使用範圍加上 ng-app="appName",或直接寫 ng-app 代表全域。
  3. 用 ng-controller="Ctrl" 指定控制器。

以下所有小範例都必須放在帶有 ng-app 的作用區域內才會生效。

1. Hello World:雙向資料綁定

用 ng-model 把輸入框與某個變數綁在一起,畫面就會即時同步:

<label for="name">name:</label>
<input type="text" ng-model="name" id="name"/>
<hr>
hello:{{name || 'liteng'}}

輸入任何字,右側文字立刻改變;空白時則顯示預設值 liteng,這是 || 在表達式中當作預設值的手法。

示範:https://2.liteng.sinaapp.com/angularjsTest/helloangularjs.html

2. 事件綁定小案例

<div>
  單價:<input type="number" min=0 ng-model="price" ng-init="price=299">
  數量: <input type="number" min=0 ng-model="quantity" ng-init="quantity=1">
  <br>
  總價:{{(price) * (quantity)}}
</div>

這裡用到了 HTML5 的 input type="number",以及 ng-init 設定初始值。表達式裡可以直接寫運算,總價會隨輸入即時重算。

示範:https://2.liteng.sinaapp.com/angularjsTest/event-bind.html

3. ng-init:指定屬性預設值

<p ng-init="value='hello world'">{{value}}</p>

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-init.html

4. ng-repeat:迭代資料

<div ng-init="friends=[{name:'Jhon',age:25},{name:'Mary',age:28}]"></div>
<p>我有{{friends.length}} 朋友。他們是</p>
<ul>
  <li ng-repeat="friend in friends">
    [{{$index+1}}]:{{friend.name}} 年齡為:{{friend.age}}
  </li>
</ul>

ng-repeat 的作用類似迴圈,$index 是內建的索引變數。

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-repeat.html

5. ng-click/ng-dblclick:DOM 事件

<div ng-controller="ctrl">
  <button ng-dblclick='showMsg()'>{{a}}</button>
</div>
<script>
function ctrl($scope){
    $scope.a = 'hello';
    $scope.showMsg = function(){
        $scope.a = 'world';
    };
}
</script>

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-click.html

6. ng-show 與 ng-hide:控制顯示

注意:ng-show="!xx" 前面加驚嘆號代表「xx 為假時顯示」。

<div ng-show="!show">
  ng-show="!show"
</div>
<div ng-show="show">
  ng-show="show"
</div>

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-show.html、 https://2.liteng.sinaapp.com/angularjsTest/ng-hide.html

7. 用 ng-show 做 toggle 效果

<h2>toggle</h2>
<a href ng-click="showLog=!showLog">顯示 logo</a>
<div ng-show="showLog">
  <img ng-src="https://liteng.org/sites/default/files/logo.png" alt="">
</div>

點擊連結把旗標取反,就能實現開關切換。

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-toggle.html

8. ng-style:動態樣式

請注意格式:字串值必須用引號包住。

<div ng-style="{width:100+'px',height:200+'px',backgroundColor:'red'}">
  box
</div>

示範:https://2.liteng.sinaapp.com/angularjsTest/ng-style.html

9. filter:格式化輸出

<div>{{9999|number}}</div>            <!-- 9,999 -->
<div>{{9999+1 |number:2}}</div>        <!-- 10,000.00 -->
<div>{{9*9|currency}}</div>            <!-- $81.00 -->
<div>{{'hello world' | uppercase}}</div><!-- HELLO WORLD -->

示範:https://2.liteng.sinaapp.com/angularjsTest/filter.html

10. ng-include:載入模板

<div ng-include="'tpl.html'"></div>

tpl.html 內容:

<h1>hello</h1>

示範:https://2.liteng.sinaapp.com/angularjsTest/show-tpl.html

11. $http:發送請求

<div class="container" ng-controller="TestCtrl">
  <h2>HTTP 請求-方法 1</h2>
  <ul>
    <li ng-repeat="x in names">
      {{x.Name}}+{{x.Country}}
    </li>
  </ul>
</div>

<h2>方法 2</h2>
<div ng-controller="TestCtrl2">
  <ul>
    <li ng-repeat="y in info">
      {{y.aid}}+{{y.title}}
    </li>
  </ul>
</div>

<script>
// 方法 1:完整 config 物件 + success / error 回呼
var TestCtrl = function($scope, $http){
    var p = $http({
        method: 'GET',
        url: 'json/date.json'
    });
    p.success(function(response, status, headers, config){
        $scope.names = response;
    });
    p.error(function(status){
        console.log(status);
    });
};

// 方法 2:簡潔的 get 寫法
function TestCtrl2($scope, $http){
    $http.get('json/yiqi_article.json').success(function(response){
        $scope.info = response;
    });
}
</script>

示範:https://2.liteng.sinaapp.com/angularjsTest/ajax.html

補充說明

範例中的 $http().success() 與 .error() 是舊版寫法,在較新的 AngularJS 中已被 .then() 取代(success/error 在 1.6 版後移除)。此外,全域函式作為控制器(如 function TestCtrl(...))也不再建議,應改用 app.controller('TestCtrl', function(){}) 註冊。

以上所有程式碼:https://github.com/litengdesign/angularjsTest
線上 demo:https://2.liteng.sinaapp.com/angularjsTest/index.html

至於 AngularJS 的路由(router)與自訂指令(directive),將另篇說明。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved