Removing items from an array in Angular when a checkbox is checked

I'm looking to iterate through a checklist and remove completed items from the array. Here's my current code:

 app.controller("MainController", ["$scope",function($scope) {
$scope.list = [{
    text: 'Figure your stuff out',
    done: false
  }, {
    text: 'Count to seven',
    done: false
  }
];


$scope.addTask = function() {
  $scope.list.push({
    text: $scope.fromListText,
    done: false
  });
  $scope.fromListText = '';
};
$scope.removeCompleted = function(index) {
  $scope.list.splice(index, 1);

}

This is my HTML:

    <html>

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6878881938a8794c88c95a6d7c8d2c8d6cb9485c8d4">[email protected]</a>" data-semver="1.4.0-rc.2"        src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
  <script data-require="angular-route@*" data-semver="1.4.0-rc.2" src="https://code.angularjs.org/1.4.0-rc.2/angular-route.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="app.js"></script>
  <script src="script.js"></script>

</head>

<body ng-app="toDoList">
  <div class="header">
    <div class="container">
      <h1>Your list brah</h1>
    </div>
  </div>
  <div class="myList" ng-controller="MainController">
    <div class="container">

      <div ng-repeat="task in list">

        <form class = "myTask">
          Task:
          <br>
          <input type="checkbox" ng-model = "task.done">{{ task.text  }} 
        </form>


      </div>
      <form>
        <input placeHolder="Things I dont want to do..." type="text" ng-  model="fromListText" ng-model-instant/>
        <button class = "myButton" ng-click = addTask() >Add task</button>
      </form>

      <button class = "myButton" ng-click = "removeCompleted()" >Clear Completed Tasks</button>
    </div>
  </div>



</body>

</html>

I'm fairly new to scripting, so all I need is something to check if the checkbox is true and then remove it. You can view the code in action on this Plunkr link: Plunkr Link

Answer №1

In order to properly implement the removeCompleted function, you must:

var $scope = {}

$scope.list = [{
    text: 'Organize your belongings',
    done: true
  }, {
    text: 'Read a book',
    done: false
  }, {
    text: 'Write a report',
    done: true
  }, {
    text: 'Exercise regularly',
    done: false
  }
]

for(var i = 0; i < $scope.list.length; i++) {
    if($scope.list[i].done)  {
    $scope.list.splice(i, 1)
     i--
    }
}

$scope.list.forEach(function(item) {
  alert(item.text + ', ' + item.done)
})

This code snippet will iterate through each item in the list and remove it if the 'done' property is set to true.

Answer №2

For instance:

$scope.removeCompletedTasks = function () {
    for (var index = $scope.tasks.length - 1; index >= 0 ; index--) {
        if ($scope.tasks[index].Completed) {
            $scope.tasks.splice(index, 1);
        }
    }
}

Take a look at this example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement basic user authentication using jQuery and Ajax

I'm currently working on setting up a basic authentication system through the browser, but I'm facing some challenges. If I remove this script, the browser's default authentication will take over. However, I want to inform the browser that ...

Error: Axios return value is undefined if user is not found by the function

Trying to retrieve error messages from Express server using Redux Toolkit has presented some challenges. When no user is found, an error message is sent with a status code. Postman works fine in getting the error response but encountering issues on the cli ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...

Can someone please provide a reference to an online illustration of implementing TinyMCE with a print format similar to Microsoft Word

Are there any online resources demonstrating the use of TinyMCE with a print layout resembling Word, with visible page breaks? Alternatively, are there any other WYSIWYG editors with a built-in print layout feature available for open source use? ...

Activate the extended view of a Material-UI Accordion

When using Accordions to display editable entities, we often want to keep modified entities in the expanded state. Currently, we have had to duplicate functionality by lifting up the expanded state into the accordion wrapper to prevent any controlled <- ...

error encountered when working with date arrays in JavaScript

I find myself perplexed by this particular issue. Although the following code snippet appears to function correctly, it exhibits some peculiar behavior. var tmpcurdte = eval(dataSource[i].startDate); tmpcurdte.setDate(tmpcurdte.getDate() + 1); while (tm ...

Is it possible to determine the length of an array using sizeof()?

I understand that in traditional C programming, arrays cannot be dynamically sized. Given that limitation, would the following code snippet be valid? (Attempting to declare an array of characters equal in length to a double.) char bytes[sizeof(double)]; ...

Tips for reading user input in a terminal using node.js

Before deploying my code to the server, I'm looking to conduct some local node testing. How can I take terminal input and use it as an input for my JavaScript script? Is there a specific method like readline that I should be using? ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

Attempting to render an image onto a canvas and apply Caman.js for image editing purposes

Currently, I have a code snippet that allows me to draw an image onto a canvas. Here is the code: var imageLoader = document.getElementById('imageLoader'); imageLoader.addEventListener('change', handleImage, false); var ...

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

What is the best way to implement a keypress event in this code?

As a JavaScript and jQuery newbie, I have a question regarding adding a simple key press action to this code. How can I implement functionality where pressing the Right Arrow key takes me to the next image, and pressing the Left Arrow key takes me to the p ...

Add an event listener to a specific class in order to control the visibility of its child elements by

Whenever I click on the "title text" link, the <ol> element refuses to hide, despite my efforts. After thoroughly reviewing the jQuery documentation and scouring Stack Overflow for answers related to .click(), .children(), .toggle(), and .hide(), I a ...

Exploring ways to utilize fetch results within a return statement in React

I have fetched data that is displayed as shown below. Now, I am trying to figure out how to render this fetch in the return statement within the results div. Does anyone have any ideas on how to achieve this? I attempted using a map function because I assu ...

Get specific choices from a drop-down menu based on its grouping options

Looking for help to extract this data cleanly using code. I was under the impression that there was a method already available that could retrieve this data in the desired format. Here's an example of a multiple select: <select id="xpto" ...

Unable to access property 'map' of undefined - error occurred while processing JSON data in line test.js:11

I'm attempting to utilize the json file in the test component below, but I keep encountering the error: TypeError: Cannot read property 'map' of undefined. I have modified the file within the test.js component, and when testing it with a sa ...

Add Content to Textbox by Clicking

In my current setup, I have a variety of buttons that, when clicked, should add the text from the button to a text box. Each time a button is clicked, I want the text to be appended to whatever is already in the input field. Current Approach $('#js- ...

Toggle the visibility of the left sidebar by hovering the mouse over it

How can I use CSS/JS to create a toggle function for my left sidebar on mouse hover? I want the Google iframe to display across the entire page when the mouse is in the middle, and the sidebar to appear with the Google iframe at a reduced size when the mou ...