MVVM基本功,KO範例4 - 以清單方式呈現資料。
<!DOCTYPEhtml>
<htmlng-app="sampleApp">
<head>
<metacharset="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>
<bodyng-controller="defaultCtrl">
<inputtype="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>
<trng-repeat="user in model.users">
<td><span>{{ user.id }}</span>
</td>
<td><span>{{ user.name }}</span>
</td>
<td><spanstyle='text-align: right'>{{ user.score }}</span>
</td>
<td><ang-click="model.removeUser(user)"class="btn">移除</a>
</td>
</tr>
</tbody>
</table>
<scriptsrc="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>
在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