MVVM基本功,KO範例4 - 以清單方式呈現資料

<!DOCTYPE html>
<html ng-app="sampleApp">
 
<head>
  <meta charset="utf-8">
  <title>Lab 4 - 物件陣列繫結清單顯示</title>
    <style>
        table { width: 400px }
        td,th { border: 1px solid gray; text-align: center }
        a.btn { text-decoration: underline; cursor: pointer; color: blue; }
    </style>  
</head>
<body ng-controller="defaultCtrl">
  <input type="button" value="新增User" ng-click="model.addUser()" />
<span>{{ model.users.length }}</span> 筆, 
  合計 <span>{{ model.calcTotalScore() | number:0 }}</span>
  <table>
    <thead>
      <tr>
        <th>Id</th>
        <th>姓名</th>
        <th>積分</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="user in model.users">
        <td><span>{{ user.id }}</span>
        </td>
        <td><span>{{ user.name }}</span>
        </td>
        <td><span style='text-align: right'>{{ user.score }}</span>
        </td>
        <td><a ng-click="model.removeUser(user)" class="btn">移除</a>
        </td>
      </tr>
    </tbody>
  </table>
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
  <script>
    angular.module("sampleApp", [])
    .controller("defaultCtrl", function($scope) {
 
      //很簡單的User資料物件
      function UserViewModel(id, name, score) {
        var self = this;
        self.id = id;
        self.name = name;
        self.score = score;
      }
 
      function myViewModel() {
        var self = this;
        self.users = [];
        self.removeUser = function(user) {
          self.users.splice(self.users.indexOf(user), 1);
        };
        var c = 3;
        self.addUser = function() {
          var now = new Date(); //用時間產生隨機屬性值
          self.users.push(new UserViewModel(
              "M" + c++,
              "P" + "-" + now.getSeconds() * now.getMilliseconds(),
              now.getMilliseconds()));        
        };
        self.calcTotalScore = function() {
          var sum = 0;
          $.each(self.users, function(i, user) {
            sum += user.score;
          });
          return sum;
        };
      }
      vm = new myViewModel();
      vm.users.push(
        new UserViewModel("M1", "Jeffrey", 32767));
      vm.users.push(
        new UserViewModel("M2", "Darkthread", 65535));
      $scope.model = vm;
      
    });
  </script>
</body>
 
</html>

Live Demo

在NG,ng-repeat="item in array"相當於KO的data-bind="foreach: array",但有兩點差異:

1) ng-repeat標註在重複出現的元素上(例如: <li>, <tr>),而KO foreach則寫在容器元素(例如: <ul>, <tbody>
2) ng-repeat用"item in array"為陣列元素指定臨時命名(即"item"),迴圈內用item.propName繫結

至於積分加總,寫一個計算函數跑迴圈就好,只要新增、刪除陣列元素動作寫在ng-click事件內,NG都能感應到變化自動重算。

繼續看KO範例5 - 即時反應物件屬性變化,如果陣列元素未增減,只是數值改變,NG也會重新加總嗎? 答案是: 會! 加總函數維持不變,加入改分數按鈕,單筆數字改變也會自動重算,請看Live Demo

[NG系列]
http://www.darkthread.net/kolab/labs/default.aspx?m=post&t=angularjs

Comments

# by AYS

想請問一下,利用ng-repeat產生的input欄位跟ng-repeat取自json array的值之間的即時運算結果,算出單筆總合的話直接算就好,但要算出每一個欄位的值總合的話我該怎麼寫? (有圖比較好懂) ↓ http://1drv.ms/1Q08X4B

# by Jeffrey

to AYS, 加總可參考範例的calcTotalScore函式,它在有任何風吹草動(修改數字、按按鈕…)時就會重算,如果對效率要求不要太高求,它的邏輯非常單純,資料在一兩百列以下的情境應可適用。

# by AYS

謝謝,我一定是當時腦子壞了才問這麼基本的問題= =|||

Post a comment