Unable to understand delete process while writing todo list in AngularJS

I am trying to write a todo application in Angularjs in the following code.

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>
Run codeHide result

In the following code, I have the following questions. How does the delete operation work?

My understanding: 1) It pushes the existing array to a new array 2) It clears the exisitng array 3) Iterates over the new array 3) Checking the functions performed ??? (When he says! X.done, is it true or false ???) Any help would be greatly appreciated.

+4
source share
1 answer

Take the steps

$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);
    });
}

Basically it only pushes done:falseinto a new version $scope.todosthat effectively removesdone:true

+1

Source: https://habr.com/ru/post/1657168/


All Articles