function DemoCtrl($scope) { //先預設給畫面上的待辦清單資料 $scope.title = '我的待辦清單'; //給ng-repeat使用的資料列表 $scope.dataList = [{ checked: false, name: '完成第一篇文章' }, { checked: true, name: '到茶行買茶包' }, { checked: false, name: '研究AngularJS' }] //更新 待辦事項總數量/完成待辦數量/未完成待辦數量 事件 $scope.updateCount = function() { //先把數量歸0 $scope.allCount = 0; $scope.finishCount = 0; $scope.unfinishCount = 0; angular.forEach($scope.dataList, function(item) { $scope.allCount++; if (item.checked) { $scope.finishCount++; } else { $scope.unfinishCount++; } }) } //預設第一次就執行此方法 $scope.updateCount(); //定義刪除事件 $scope.delete = function(index) { //對array物件 $scope.dataList.splice(index, 1); //更新數量 $scope.updateCount(); } }
<div ng-app> <div ng-controller="DemoCtrl"> <!-- 標題 --> <h2>{{title}}</h2> <!-- 副標題 --> <h3>共{{allCount}}項事件,已完成{{finishCount}}項,未完成{{unfinishCount}}項</h3> <!-- Todo列表 --> <div> <!-- ng-repeat開始 --> <li ng-repeat="item in dataList"> <input type='checkbox' ng-model="item.checked" ng-click="updateCount()" /> {{item.name}} <input type='button' value='刪除' ng-click="delete($index)"> </li> <!-- ng-repeat結束 --> </div> </div> </div>