4

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>

In the following code ,I have the following questions. How is the delete operation working??

My understanding: 1)It pushes the existing array into a new array 2)It clears the exisitng array 3)Iterates over the new array 3)Checking the done functionality??? (When it says !x.done , is it true or false???) Any help would be highly appreciated.

Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
mohan babu
  • 1,388
  • 2
  • 17
  • 35

1 Answers1

1

Walk through 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 the done:false into new version of $scope.todos which effectively removes the done:true

charlietfl
  • 170,828
  • 13
  • 121
  • 150