function DemoCtrl($scope) { //先預設給畫面上的待辦清單資料 $scope.title = '我的待辦清單'; //給ng-repeat使用的資料列表,預設為空陣列 $scope.dataList = []; //監聽事件 $scope.$watch('dataList', function() { $scope.updateCount(); }, true); //更新 待辦事項總數量/完成待辦數量/未完成待辦數量 事件 $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.delete = function(index) { //對array物件刪除元素 $scope.dataList.splice(index, 1); } //定義新增事件 $scope.add = function() { if ($scope.newEvent == '') { alert('請輸入待辦事項'); } else { var data = { checked: false, name: $scope.newEvent } $scope.dataList.push(data) $scope.newEvent = ''; } } }
<div ng-app> <div ng-controller="DemoCtrl"> <!-- 標題 --> <h2>{{title}}</h2> <!-- 副標題 --> <h3>共{{allCount || 0}}項事件,已完成{{finishCount || 0}}項,未完成{{unfinishCount || 0}}項</h3> <!-- Todo列表 --> <div> <h4>待辦事項</h4> <!-- ng-repeat開始 --> <li ng-repeat="item in dataList"> <input type='checkbox' ng-model="item.checked" ng-checked="allchecked" /> {{item.name}} <input type='button' value='刪除' ng-click="delete($index)"> </li> <!-- ng-repeat結束 --> </div> <!-- 新增事件 --> <div> <h4>新增待辦事項</h4> <input type='text' ng-model='newEvent'> <input type='button' value='新增' ng-click='add()'> </div> </div> </div>