AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background.

If I try to delete the last row, it gets deleted but the color remains for the first row only (it should be for both the first and second rows).

Check out this example in Plnkr: try deleting the last row by clicking on the 'x' in the University column.

http://plnkr.co/edit/6td3Ywfeoe502wsQFNGO?p=preview

Here is the code in index.html:

<!DOCTYPE html>
<html ng-app>
<head>
    <title></title>
    <script src="script.js" ></script>
    <script src="http://code.angularjs.org/1.1.5/angular.min.js" ></script>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
    <label>Search:</label>
<input type="search" ng-model="search" placeholder="Enter to Search">
    </div>
<div id="table1" ng-controller="table">
    <table  cellpadding="0" border="0" cellspacing="0"  >
        <tr id="heading">
            <th>Roll NO:</th>
            <th>Student Name:</th>
            <th>University:</th>
        </tr>
        <tr class="color2" ng-class="student.color" ng-repeat="student in students | filter:search | filter:new_search">
            <td>{{student.Rollno}} <input type="checkbox" ng-model="checked[$index]"> </td>
            <td>{{student.Name}}</td>
            <td>{{student.Uni}} <button ng-click="remove($index)">x </button></td>
        </tr>
    </table>
    <div >
        <label>Rollno:</label>
        <input type="number" ng-model="new_rollno"> <br>
        <label>Name:</label>
        <input type="text" ng-model="new_name"><br>
        <label>University:</label>
        <input type="text" ng-model="new_uni"><br>
        <button ng-click="save()">Save</button>
    </div>
    <div style="float: right; margin-right: 300px;margin-top: -200px;">

    <button ng-click="remove($index)" >Remove</button>
</div>
</div>
</body>
</html>

The code in script.js is as follows:

// Code goes here

    var table = function($scope)
    {
     $scope.students=[
         {Rollno: "1122",Name: "abc",Uni: "res",color:"red"},
         {Rollno: "2233",Name: "def",Uni: "tuv",color:"red"},
         {Rollno: "23432",Name: "g325325hi",Uni: "wxy"},
         {Rollno: "3344",Name: "ghi",Uni: "wxy"}
     ];
     $scope.save=function(){
     $scope.students.push({
     Rollno: $scope.new_rollno,
     Name: $scope.new_name,
     Uni: $scope.new_uni
     });
         $scope.new_rollno="";
         $scope.new_name="";
         $scope.new_uni=""
     };
     $scope.checked=[];
      $scope.remove=function(index){
          alert($scope.checked);
          $scope.students.splice(function(record){
              return $scope.checked[$index];
          },1);
      };
    };

Answer №1

The main issue with the code is that the first parameter for the splice function should be the start index, but you are trying to pass a function instead. If you use the passed index, everything works fine.

$scope.students.splice(index,1);

In the code snippet provided, you can see that even when you delete the last row, everything continues to work correctly.

angular.module('app', [])
  .controller('tableCtrl', ['$scope',
    function($scope) {
      $scope.students = [{
        Rollno: "1122",
        Name: "abc",
        Uni: "res",
        color: "red"
      }, {
        Rollno: "2233",
        Name: "def",
        Uni: "tuv",
        color: "red"
      }, {
        Rollno: "23432",
        Name: "g325325hi",
        Uni: "wxy"
      }, {
        Rollno: "3344",
        Name: "ghi",
        Uni: "wxy"
      }];
      $scope.save = function() {
        $scope.students.push({
          Rollno: $scope.new_rollno,
          Name: $scope.new_name,
          Uni: $scope.new_uni
        });
        $scope.new_rollno = "";
        $scope.new_name = "";
        $scope.new_uni = ""
      };
      $scope.checked = [];
      $scope.remove = function(index) {
        $scope.students.splice(index, 1);
      };
    }
  ])
/* Styling rules go here */

table {
  width: 100%;
}
table,
th,
td {
  border: 1px solid black;
}
.color {
  background-color: lightgray;
}
.color2 {
  background-color: white;
}
#heading {
  background-color: black;
  color: white;
}
tr:hover {
  background-color: darkblue;
  color: white;
  font-weight: bold;
}
#images img {
  margin-top: 10px;
}
#img1 {
  width: 33.4%;
}
#img2 {
  width: 66%;
  height: 255px;
}
#table1 {
  margin-top: 10px;
}
label {
  display: block;
  margin-bottom: 5px;
  margin-top: 5px;
}
button {
  margin-top: 5px;
  padding: 5px;
}
.red {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-app="app" ng-controller="tableCtrl">
  <div>
    <label>Search:</label>
    <input type="search" ng-model="search" placeholder="Enter to Search">
  </div>
  <div id="table1">
    <table cellpadding="0" border="0" cellspacing="0">
      <tr id="heading">
        <th>Roll NO:</th>
        <th>Student Name:</th>
        <th>University:</th>
      </tr>
      <tr class="color2" ng-class="student.color" ng-repeat="student in students | filter:search | filter:new_search">
        <td>{{student.Rollno}}
          <input type="checkbox" ng-model="checked[$index]">
        </td>
        <td>{{student.Name}}</td>
        <td>{{student.Uni}}
          <button ng-click="remove($index)">x</button>
        </td>
      </tr>
    </table>
    <div>
      <label>Rollno:</label>
      <input type="number" ng-model="new_rollno">
      <br>
      <label>Name:</label>
      <input type="text" ng-model="new_name">
      <br>
      <label>University:</label>
      <input type="text" ng-model="new_uni">
      <br>
      <button ng-click="save()">Save</button>
    </div>
    <div style="float: right; margin-right: 300px;margin-top: -200px;">


    </div>
  </div>
</div>

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

Select an item from the options available

Looking to automatically select a specific item from a combobox upon clicking a button on my webpage. The page includes both PHP and JavaScript code for this functionality. Currently, I have a JavaScript function triggered by the "onclick" event of the bu ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Ensure that it is safe to bypass Vue's built-in sanitization on this specific Vue component for the href attribute

I encountered an issue with a .vue file that contains an anchor tag as shown below: <a class="login_class" :href="loginUrl">Use Universal Login</a> When running Sonar, it raises a warning regarding the :href attribute: En ...

Exploring the power of Foundation For Apps and Angular by seamlessly displaying dynamic data sourced from

I'm currently working with Foundation for Apps, a framework that incorporates elements of AngularJS. My goal is to display the content from a local JSON file by accessing it through a controller and rendering the results as 'cards'. Addition ...

Dealing with errors in Node.js using the Express framework and the

The code I'm having trouble with is shown below app.get('/', function(req, res, next) { if (id==8) { res.send('0e'); } else { next(); } }); app.use(function(err, req, res, next){ res.send(500, ' ...

What is an alternative way to display static images in Rails 5 without relying on the Asset Pipeline?

I developed a web-based application with the backend built on Rails 5. Utilizing AngularJS for the frontend, I opted to not use the Asset Pipeline to deliver static content. Instead, I loaded all my scripts (JS & CSS) in the index.html file located within ...

The Angular script encounters a 404 error when attempting to load a Web API through the URL

My WebAPI method can be accessed here: http://localhost:50463/api/movies When I access this method from a browser, it loads perfectly without any issues. However, within my project (where the Web API is located), when I try to call the method from Angul ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

Troubleshooting: Issues with React Material-UI breakpoints not functioning

Trying to create a responsive navbar using Material-UI. The goal is to hide the IconButton between 960px and 1920px, and display it from 0px to 960px. However, it seems to work only below 960px. Here's a snippet of the code for IconButton and ul: ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

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 ...

Creating dynamic DIVs that adjust fluidly to different screen

I have a section containing 4 centered divs. Here is what I want to achieve: When the screen width is over 1280px, display all 4 divs in a row. When the screen width is less than 1280px, show 2 divs per row. And when the screen width is under 640px, disp ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

AngularJS Component enthusiasts

While going through a tutorial on the Angular UI Router GitHub page (link: https://github.com/angular-ui/ui-router), I came across an intriguing code snippet: var myApp = angular.module('myApp', ['ui.router']); // For Component users, ...

Is it feasible to merge Apollo queries within the context of Nuxt?

Incorporating nuxt and apollo together using the https://github.com/nuxt-community/apollo-module module has been a successful venture. A GraphQL query was crafted and tested in GraphiQL to obtain information about a specific page along with general SEO de ...

An elegant approach to converting a JavaScript object containing key-value pairs into an array of objects, each with a single key-value pair

Essentially, I have an enum that represents different statuses status = {1: "new", 2: "working" ... } and my goal is to transform it into something like status = [{1: "new"}, {2: "working"} ...] in a way that is cl ...

Why is a question mark added to the URL when the login button is clicked

I've encountered an issue where clicking this code for the first time redirects me to localhost:8080//? instead of localhost:8080//admin.html. Any idea why this is happening? $("#admin-login").click(function(){ var data = {"username": $("#admin ...

PHP code isn't showing any posts

Context: I have implemented a PHP loop to generate a dynamic feed of my portfolio posts on my WordPress website. Issue: The first five posts are being displayed correctly, but the subsequent posts are not. I'm uncertain about the underlying cause and ...