2016-10-09 25 views
4

我正嘗試在以下代碼中編寫一個待辦事宜應用程序。在AngularJS中編寫待辦事項列表時,無法理解刪除過程

function write_controller($scope){ 
 
    $scope.todos = [{text:'hey all',done:false}, 
 
       {text:'hello',done:false}]; 
 
    $scope.addtodo = function(){ 
 
    $scope.todos.push({text:$scope.todopush,done:false}); 
 
    $scope.todopush = ''; 
 
    } 
 
    $scope.delete = function(){ 
 
    var oldtodos = $scope.todos; 
 
    $scope.todos = []; 
 
    angular.forEach(oldtodos, function(x){ 
 
     if (!x.done){ 
 
     $scope.todos.push(x);} 
 
    }); 
 
    }; 
 
}
<html ng-app> 
 
    <head> 
 
    <script src = 
 
    "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> 
 
     </script> 
 
     </head> 
 
     <body> 
 
     <div class = "basic_class" ng-controller = "write_controller"> 
 
     <ul> 
 
     <li ng-repeat = "todo in todos"><input type = "checkbox" ng-model 
 
     ="todo.done">{{todo.text}}</input></li> 
 
     </ul> 
 
     <input type = "text" 
 
     placeholder = "please add data here" 
 
     ng-model="todopush"> 
 
     </input> 
 
     <input type = "button" ng-click ="addtodo()" value ="Click me!!"></input> 
 
     <input type = "button" ng-click = "delete()" ng-model="remove" value = 
 
     "remove!"></input> 
 
     </div> 
 
</body> 
 
</html>

在下面的代碼,我有以下幾個問題。 刪除操作如何工作?

我的理解: 1)推動現有陣列到一個新的數組 2)清除exisitng陣列新數組 3)檢查完成的功能 3)迭代過??? (當它說!x.done,它是真的還是假的?) 任何幫助將不勝感激。

+0

你做這個代碼?根據代碼刪除不會工作 – Sajeetharan

+0

@Sajeetharan爲什麼不...爲我工作 – charlietfl

+0

如果你打算分享代碼,使用jsfiddle或類似的東西。 – r1verside

回答

1

通過一系列步驟

$scope.delete = function() { 
    // store existing todos array in variable 
    var oldtodos = $scope.todos; 
    // create new empty array for todos 
    $scope.todos = []; 
    // loop over previously stored todos 
    angular.forEach(oldtodos, function(x) {//x is element of the array - a single todo object 
     // if x.done is not truthy 
     if (!x.done){ 
     // push this item into `$scope.todos` 
     $scope.todos.push(x); 
    }); 
} 

基本上只推done:false$scope.todos新版本,它有效地消除了done:true

+0

點擊一個複選框,完成從false更新爲true的過程如何? –

+1

'ng-model =「todo.done」''參見:https://docs.angularjs.org/api/ng/directive/ngModel – charlietfl

+1

簡短答案是'ng-model'綁定到數據模型對象並且將會改變當複選框更改時 – charlietfl