AngularJS(一)Demo

轉載出處:http://www.cnblogs.com/liulangmao/p/3700919.html


入門實例:

 

一個購物車產品清單,可以自行改變數量,總價自動計算的小例子:

代碼如下:

複製代碼
<!DOCTYPE html>
<html ng-app>
<head>
  <title>1.1實例:購物車</title>
  <meta charset="utf-8">
  <script src="../angular.js"></script>
  <script src="script.js"></script>
  <style type="text/css">
    .red {
      color:#cc0000
    }
    * {
      font-family:'MICROSOFT YAHEI'
    }
    TD {
      font-size:12px; color:#999;
    }
  </style>
</head>
<body >
  <div ng-controller="CarController">
    <h1>your shopping cart</h1>
    <table>
      <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td><input ng-model="item.quantity"/></td>
        <td>{{item.price|currency}}</td>
        <td class="red">{{item.price*item.quantity|currency}}</td>
        <td><button ng-click="remove($index)">remove</button></td>
      </tr>
    </table>
  </div>
</body>
</html>
複製代碼

script.js代碼:

複製代碼
function CarController ($scope) {
    $scope.items = [
        {"title":"兔子","quantity":1,"price":"100"},
        {"title":"喵","quantity":1,"price":"200"},
        {"title":"狗只","quantity":1,"price":"400"},
        {"title":"倉鼠","quantity":1,"price":"300"}
    ];
    $scope.remove = function(index){
        $scope.items.splice(index,1)
    }
}
複製代碼

下面對以上代碼進行說明:

1.ng-app:

<
html ng-app>:

ng-app屬性,用來告訴頁面哪一部分需要使用angular管理.通常情況下都這樣管理.
(但是我在師傅的網站上看到不是這樣的,是加在其它div上面的,而且是有值的.這個學到後面再說)

2. ng-controller:
<div ng-controller="CarController">

使用一個控制器來控制頁面中的某個區域,這裏就是管理這個<div>到</div>裏的所有內容
這裏使用的控制器就是script.js裏定義的CarController函數

3. ng-repeat:
<tr ng-repeat="item in items">

循環當前的標籤(包括裏面的內容和自己),循環中的當前變量就是item,item在當前作用域的items變量裏進行循環
即CarController裏定義的$scope.items數組

4. {{ }}:
<td>{{item.title}}</td>

使用{{}}來動態的綁定視圖裏顯示的數據.{{}}裏就是當前作用域裏的變量

5. ng-model:
ng-model="item.quantity"

ng-model用在輸入框裏,使輸入的內容和它等於的變量數據進行綁定,
也就是說,輸入的值變化,變量就變化,變量變化,視圖上對應顯示的數據也變化


6.
currency:
<td>{{item.price|currency}}</td>

<td class="red">{{item.price*item.quantity|currency}}</td>

angular帶有過濾器特性,可以用來做文本格式的轉換,其中,currency貨幣過濾器,可以實現美元格式化


7. ng-click:
<button ng-click="remove($index)">remove</button>

爲元素綁定click事件的回調,點擊後就調用作用域下的remove方法,也就是在CarController中添加的remove方法


8. $index:
remove($index)

$index是在ng-repeat過程中的循環的索引值,從0開始


9. 控制器:
function CarController ($scope) {
...
}

控制器負責管理相關的區域的邏輯.函數的形參$scope就是當前區域的作用域,區域中的變量,方法,都從它的作用域中尋找.
比如這裏的$scope.items和$scope.
remove


10. 另外,ng-repeat所創建的列表是和數據的更新事實綁定的,所以當使用remove方法刪除數據中的某一組數據,那麼,視圖中相應的ui也會被刪除.

相關代碼託管:
https://github.com/OOP-Code-Bunny/angular
發佈了0 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章