javascript - 在 AngularJS 中编写待办事项列表时无法理解删除过程

标签 javascript angularjs arrays html ng-app

我正在尝试使用以下代码在 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)清除现有数组 3)遍历新数组 3)检查完成的功能??? (当它说 !x.done 时,它​​是真还是假???) 任何帮助将不胜感激。

最佳答案

完成步骤

$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

关于javascript - 在 AngularJS 中编写待办事项列表时无法理解删除过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939751/

相关文章:

javascript - 有没有办法选择表单的所有输入元素,包括表单之外的元素?

javascript - 有没有办法中途暂停 CSS 过渡?

javascript - 对 JavaScript 多维数组中的元素进行排序

javascript - 成功时拒绝 $http promise

javascript - 如何避免 $http 请求后重复 .then() 和 .catch() ?

angularjs - Angular 基础教程不适用于 Windows?

c++ - std::inner_product 比手动快 4 倍,但没有使用 SIMD?

java - 这个 javacode 究竟做了什么?

javascript - isChild(节点1,节点2)

c - 从C中的数组中删除负数