angular學習筆記(一)-入門案例


入門實例:

 

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

代碼如下:

<!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




 
 






 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM