Differentiating row colors in an HTML table using ng-repeat

I am trying to color the rows of a table alternatively with green and yellow using ng-repeat. I initially attempted to do this without ng-repeat and it worked as expected.

.table-striped>tbody>tr:nth-of-type(odd)
    {
        background: yellow !important;
    }

    .table-striped>tbody>tr:nth-of-type(even)
    {
        background: green !important;
    }
<html>
  <div><table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody>
           <tr>
                <td>{{value.val1}}</td>
             </tr>
          <tr>
                <td>{{value.val2}}</td>
            </tr>
          <tr>
                <td>{{value.val3}}</td>
            </tr>            
        </tbody>
    </table>
    </div>
  <html>

However, when I tried implementing the same functionality with ng-repeat, all rows turned out to be yellow. I need help to resolve this issue. Thank you in advance.

.table-striped>tbody>tr:nth-of-type(odd)
    {
        background: yellow !important;
    }

    .table-striped>tbody>tr:nth-of-type(even)
    {
        background: green !important;
    }
<html>
  <div><table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody ng-repeat="value in values">
           <tr>
                <td>{{value.val1}}</td>
             </tr>         
        </tbody>
    </table>
    </div>
  <html>

Answer №1

In my opinion, it is more appropriate to use ng-repeat="value in values" on the tr element rather than on the tbody element. Applying ng-repeat directly on the tbody will cause the body element itself to be repeated.

Answer №2

One way to customize the appearance of your rows is by dynamically assigning classes and then applying styles as needed.

<tr class="customrow">

$(".customrow:odd").addClass("oddstyle");
$(".customrow:even").addClass("evenstyle");

Answer №3

If you want to add alternating row colors in a table, you can utilize the ng-class-odd directive with the specified classname.

<html>
  <div>
     <table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody ng-repeat="value in values">
           <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val1}}</td>
             </tr>
          <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val2}}</td>
            </tr>
          <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val3}}</td>
            </tr>            
        </tbody>
    </table>
    </div>
  <html>

To style these alternating rows in your CSS file, you can define classes for the background colors without using !important:

.row-color {
    background: green;
}

.row-color.odd {
    background: yellow;
}

By avoiding !important, you adhere to better coding practices.

Answer №4

My suggestion for the OP is to consider moving the ng-repeat from <tbody> to <tr>. By doing this, it aligns better with their intended structure and eliminates the need for ng-repeat. However, if they choose to keep the ng-repeat at the <tbody> level, it is still possible to achieve alternative coloring using only CSS.

tbody:nth-of-type(odd)>tr {
  background-color: pink;
}

tbody:nth-of-type(even)>tr {
  background-color: purple;
}
<table>
  <tbody>
    <tr><td>row1</td></tr>
  </tbody>
  <tbody>
    <tr><td>row2</td></tr>
  </tbody>
  <tbody>
    <tr><td>row3</td></tr>
  </tbody>
</table>

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

For all URLs, redirect from HTTP to HTTPS unless the request is coming

I recently transitioned my node.js app to use https. To achieve this, I configured https through an nginx reverse proxy. However, I encountered a problem where, when I type in example.com, it does not automatically redirect to https://example.com. In an at ...

Reset ng-model when ng-show is not active in AngularJS

Hey there, I'm facing a little issue. I have an input field that sometimes needs to be displayed in a form and sometimes not. I'm worried that if someone enters data, hides it, and then hits send, the data will still be sent. That's why I w ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Move the background-position animation from outside the element to inside the element

Currently facing challenges with animating a background image from the EXTERIOR to the INTERIOR of an element. This code functions properly in Chrome only when the image remains within the boundaries of the element: <script type="text/javascript"> ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Arabic text spread across multiple lines within the queryString

When attempting to call an ASP.NET page from JavaScript with a query string containing Arabic text, I encounter an error when the code is live online but it runs smoothly on the local server. The issue seems to arise when the Arabic text spans multiple l ...

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

Adjusting the styling of slick.js carousel when the slide changes

Is it feasible to change the CSS for a div on a slick.js slider change? Essentially, I want to cycle through an array of colors and set the background color of .content to that color when the slider autoplays or when a button is clicked. Am I being too amb ...

Using parameters in a directive to invoke a function in an Angular controller's scope

This question presents a unique scenario as it involves calling a controller's functions with parameters that are only accessible within a directive. Directive (markup): <div do-something="doSomething(x)"></div> Directive (JavaScript): ...

Is there a way to check for updates after doing an NPM install with "npm install --save-dev"?

After installing various packages, I know that using --save-dev will generate a local package.json file containing them. Is there a method within npm (or the Webstorm IDE) to verify if any of these packages have been updated and then download newer versio ...

Encountering a 404 Not Found issue while trying to add scripts with Node.js

I am currently working with a node server and an HTML file, where the default route is being directed. server.js /** * Created by Creative Coder on 10/26/2015. */ var express = require('express'); var mysql = require('mysql'); var a ...

Tips for effectively utilizing the Material-UI Grid component to implement this layout

Currently, I am working on incorporating this design in Material-UI by utilizing the Grid component. To better delineate the boundaries, I have marked the container border in red for clarity. The Add button should be positioned at the far right of the c ...

Using jQuery to wrap content in parentheses when a class is detected inside them

To highlight code within parentheses() when a specific class is present, a regex can be used. The code snippet below uses jQuery to achieve this: var o = jQuery(".wp-site-blocks"); o.html(o.html().replace(/\([^\)]*?\)/g, '<span clas ...

Why am I receiving undefined for req.user in passportjs?

After setting up passportJS with my node express app, I encountered an issue where the req.user is undefined when making a login/register request. I am not sure what went wrong or if I missed something in the configuration of passport js. In my setup, I us ...

Struggling with handling multiple jQuery AJAX requests on a single webpage

Greetings, I am currently working on a PHP Project that involves loading requests using ajax. Below are the two functions in question: Function One: Upon clicking the showNotify event, an ajax request is made to retrieve content with a spinner displayed u ...

Creating a variable that is named after an existing variable

Creating a new variable with a dynamic name can be tricky. Let's take a look at an example: function preloader(imglist) { var imgs = imglist.split("|"); for (i in imgs) { var img_{i} = new Image; img_{i}.src = imgs[i]; ...

How can I show an item repeatedly with each button click in ReactJS?

Currently, I have a setup where I can display a checkbox and its label upon clicking a button. However, the limitation is that only one checkbox can be displayed at a time. Is there a way to modify this so that I can show multiple checkboxes simultaneous ...

Show error message and display in ajax response

Hey there! I have a question about using Ajax to send error messages if an error occurs, otherwise sending the view. Here is my code snippet and I would really appreciate some guidance or suggestions on what to do next: Here is an example of my code: pub ...

AngularJS: Compile a particular template

One pre tag on the page contains dynamic text that is unknown during page load. This text may include ng commands, as shown below: <pre> Hello <span ng-click="test('args')">world</span> angular-JS! </pre> Since these ...

How do I determine the dimensions of an object in Three.js?

Seeking advice on determining the size of a Three.js object. I am currently loading various objects from files and wish to find a way to automatically adjust scale or camera position to ensure the entire object fits within the frame. Since different files ...