Remove several ng-repeat items by clicking a single button

I am presenting a table detailing project names, captured in the image below.

When the delete button is clicked, I send the selected checkbox data as an array of objects to my controller:

[{id:1,name:'Name 8'},{id:2,name:'Name 7'}]

These names are then removed from the table on the server side. Everything functions properly, but how can I remove the rows from the DOM after deletion? I found this post that explains how to eliminate ng-repeat elements from the DOM, but it only removes one element at a time by passing the $index to the splice() function.

In my situation, I need to remove multiple rows. If I have to use the splice function in my controller, how do I obtain the index from the selected rows object? Alternatively, is there a more effective approach?

Hope my inquiry is comprehensible!

Update: jsFiddle

Solution: I needed to adjust @wickY26's solution slightly to match my scenario. Here is my updated jsFiddle.

What I did was in the "delete()" method, change the code to:

angular.forEach($scope.projects, function (row, index) {
            if($scope.projects[index].checked) {
                $scope.projects.splice(index,1);
            }            
        });

Answer №1

To maintain selected rows on an object, you can bind a checkbox with ng-model. For example, the HTML for a table should be structured like this:

HTML

  <table class="table table-bordered">
    <tbody>
      <tr ng-repeat="row in data" ng-class="{'success' : tableSelection[$index]}">
        <td>
          <input type="checkbox" ng-model="tableSelection[$index]" />
        </td>
        <td ng-repeat="cell in row">
          {{cell}}
        </td>
      </tr>
    </tbody>
  </table>

If you define a function in your controller to iterate through your data and splice the array based on the boolean values of the tableSelection object...

UPDATE

Following your comment, I debugged my code and realized that I couldn't remove multiple rows at once. Upon closer inspection, I made some adjustments to my code...

In my initial example, you cannot delete multiple rows simultaneously because each time you splice an element from the data array, it causes a shift in the indexes of the remaining elements. The correct approach is to start from the last index,

Here is the revised CONTROLLER

  $scope.removeSelectedRows = function() {
    //Starting from the last index avoids shifting due to array.splice()
    for (var i = $scope.data.length - 1; i >= 0; i--) {
      if ($scope.tableSelection[i]) {
        //Delete row from data
        $scope.data.splice(i, 1);
        //Remove rowSelection property
        delete $scope.tableSelection[i];
      }
    }
  };

I have updated my PLUNKER with additional comments and functionality as well...

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

React - Updating child component each time the ref.current value is changed in the parent

Is it possible to make the child component Dashboard re-render whenever the value of showOfferDescription.current changes? I have found that using useRef is necessary in this case, as opposed to useState, because callback functions triggered by game.event ...

verifying the presence of a string or value within an array

I'm currently working on a feature that involves adding an element to an array by typing something into a text field and clicking a button. I've also implemented an if statement to check if the input already exists in the table, and show an alert ...

"Adjusting the position of series data container in Highcharts JS to optimize

Currently, I am utilizing highcharts along with highcharts-ng. My goal is to adjust the position of the container for series Data (where the number 80 is displayed below) slightly higher as it is currently overlapping with the numbers 200 and -200 in the t ...

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

Is it necessary for Angular Reactive Form Validator to convert types before checking the value for min/max validation?

Preface: My motivation for asking the questions below stems from my experience with form.value.purchaseCost. When the <input> field does not have type=number, I receive a string instead of a number. This required me to manually convert it to Number ...

Form data triggering inaccurate results in ajax response

After following online tutorials and seeking help from Stack Overflow, I am still struggling with a strange issue related to AJAX. I appreciate any assistance in solving this problem. I am trying to create a feature where users can search for match result ...

What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter? I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs. function bar(resol ...

Exploring the world of XD plugins, utilizing npm packages and Node.js APIs

Is it feasible to integrate npm packages and Node.js APIs into my Adobe XD plugin development process? ...

Stop the link action following a delay after the mouse is clicked

I'm currently troubleshooting a function that should prevent users from being redirected when clicking and holding onto a link for more than one second. However, the function I implemented is not functioning as expected. I have spent some time reviewi ...

Tips for implementing pagination in a datatable using Element UI:

I am puzzled by the fact that the el-table component does not have built-in pagination functionality. While there is a separate pagination component available, there is no clear explanation on how to integrate it with an el-table. I am struggling to under ...

I was able to efficiently reverse the transition using JavaScript, but I'm puzzled as to why my alternate approach is not functioning correctly

Check out my demo on jsfiddle I am trying to implement a reverse transition when clicking the <li> again. The commented code did not work, but the code below worked perfectly: let dbclickre = true; function flipped() { if (db ...

Experiencing a bug in the production build of my application involving Webpack, React, postCSS, and potentially other JavaScript code not injecting correctly

I've encountered an issue with my webpack.prod.config when building my assets, which may also be related to the JS Babel configuration. While I can successfully get it to work in the development build by inline CSS, the problem arises when attempting ...

Having trouble transmitting data from the View to the Controller

Need help with this issue. I'm having trouble passing my data to the controller. Below is my ajax code. <script type="text/javascript"> $(document).on("click", "#login_button", function () { var userName = document.getElementById(" ...

Reload the webpage locally without sending a request to the server

My goal is to refresh the browser window without needing to hit the server. I am considering using javascript for this task. Below is the code that I have, but I'm not entirely clear on what it does! <body onload="JavaScript:AutoRefresh(5000);"> ...

Issue with injecting Angular service in unit test

Hello, I'm currently working on a simple test: define(["angular", "angularMocks", "app", "normalizer"], function(angular, mocks, app) { describe("service: normalizer", function () { var normalizerService; beforeEach(module("ADB")); b ...

Filter ng-repeat using OR condition for property

I'm trying to filter a list based on a model value entered in a text box. For example: var person={}; person.Id=1; person.Name="Test 1"; person.PetName="Rest 1" var persons=[]; persons.push(person); person.Id=2; person.Name="Test ds"; per ...

Using the variable (parameter) as a property in JavaScript

This function I'm creating will calculate the quantity of food data. const countFood = (foodType) => { let foodNeeded = 0; if (animal.food.type === foodType) { foodNeeded += +animal.food.amount; }; const food = foodType; if (foodN ...

Attach an event to the HTML document's element and utilize addEventListener on the same element

What sets apart the logical/programming difference? I found myself responding to a duplicated question and decided to change one of the repetitive answers with a fresh perspective (in my opinion, even though it appears longer): for (i = 1; i <= 10; i++ ...

Error in Typescript: Attempting to use type 'undefined' as an index is invalid.ts(2538)

I'm currently diving into typescript and struggling to understand how to resolve the error Type 'undefined' cannot be used as an index type.ts(2538) while keeping default prop values. Here is the code snippet: interface PVIconInterface { ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...