achieving alternating classes within ng-repeat without the need for data binding using scope variables

On my accordion table, I have nested ng-repeats which create child rows for each parent row. To achieve this, I structured the layout by using <tbody> for each parent item and placing the parent row within a <tr>. I then utilized ng-repeat to insert all the child rows. However, due to multiple <tbody> elements, the zebra striping on the table becomes disrupted. Additionally, the table has collapsible/expanding child rows, requiring the striping to be accurate for only the visible rows. Thus, I'm manually adding striping classes by toggling a scope variable with Angular's ng-init and applying it with ng-class.

In HTML:

    <tbody ng-repeat="parentRow in myData" ng-init="changeRowClass($even)">
        <tr ng-class="{'industry-payments-even-row': industryRowEven, 'industry-payments-odd-row': !industryRowEven}">
            <td>{{parentRow.industryCode}} - {{parentRow.industryCodeDescription}}</td>
            <td class="numeric">{{parentRow.ValueOneSum}}</td>
            <td class="numeric">{{parentRow.ValueTwoSum}}</td>
        </tr>
        <tr ng-repeat="childRow in parentRow.childIndustries" ng-init="changeRowClass($even)" ng-class="{'industry-payments-even-row': industryRowEven, 'industry-payments-odd-row': !industryRowEven}">
            <td>{{childRow.industryCode}} - {{childRow.industryCodeDescription}}</td>
            <td class="numeric">{{childRow.ValueOne}}</td>
            <td class="numeric">{{childRow.ValueTwo}}</td>
        </tr>
    </tbody>

Controller snippet:

$scope.industryRowEven = false;
$scope.changeRowClass = function(isEven) {
    $scope.industryRowEven = isEven;
};

For each iteration (parent or child), I want the class to alternate for the next row. Even though the variable toggles correctly in the debugger, the issue lies in ng-class binding to the current state in the scope. This causes it to switch the class for all rows instead of adhering to the state at the time of rendering that specific row.

I simply need the class printed based on the variable state during each row render, disregarding it until the ng-repeat starts over (e.g., for sorting or visibility changes).

Is there a method to break this binding?

Answer №1

AngularJS offers built-in functionality for alternating styles using directives like ngClassOdd and ngClassEven.

These directives mimic the behavior of ngClass, but specifically target odd/even elements within an ngRepeat loop.

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

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...

In Three.js, what causes the x and z axes to produce the same result when the camera is rotated 90 degrees?

Currently, I am in the process of creating a basic framework for a first-person-shooter game to gain a deeper understanding of all its components, particularly focusing on 3D mathematics. I have stumbled upon an issue that seems to only arise when using T ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

Certain scripts fail to load properly when using Internet Explorer

The code snippet provided only seems to be functional in Firefox, where it displays all alerts and successfully executes the displayUserLanding function. However, in Internet Explorer, the browser appears to only execute the following alert: alert("Helper ...

Is there a specific approach for linking together two AngularJs service calls and executing a function with the obtained data?

I am trying to chain two service calls together and then filter the data using a forEach loop. However, I am encountering a TypeError: "SocialMediaUserService.channelProfiles is not a function" error in Chrome. Interestingly, this code works perfectly fin ...

If you try to wrap an object with an anonymous function, you'll receive an error message

Consider the following straightforward example. (function() { var message = { display: function() { alert('hello'); } }; })(); When trying to implement message.display(); An error is triggered stating ReferenceError: message ...

Is there a way to arrange an array based on the initial value?

In my array, I have a mixture of strings and arrays. Each string corresponds to the array next to it. For example, the string 789 is associated with the array ['111A', '222B', '333C']. My goal is to sort based on the strings w ...

"Learn how to properly configure JSON data on x and y axes in the c3.js library

I rely on c3 to produce uncomplicated graphs. I am in search of a way to extract data from a Json file and use it to create my Line Graph. In order for the graph to display correctly, I need my Y values to be represented by "Labels" and my X values to be ...

Concealing certain elements within a loop using a "show more" button

In my PHP code, I am utilizing a foreach loop in the following manner: <div class="items"> @foreach($results as $details) <div class="col s2 l2"> {{ $details }} </div></div> My approach involves using the blade templating feature ...

"Can you provide me with advice on how to pass a path to fs.createReadStream

I'm new to node.js, so please bear with me if this is a basic question. I have created a script that writes data to a file and then uploads it to Slack. Here's how the data is written to the file: let myFile = '/tmp/' + Date.now() + & ...

Incorporating a Bootstrap accordion into an AngularJS webpage

Recently I encountered a problem while attempting to execute the code below in an AngularJS page. <div class='panel-group' id=accordion'> <div class="panel panel-default"> <h4 class="panel-title"> ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

The website experiences performance issues when large amounts of data are being uploaded

Our internal team website is built using Python Django and AngularJS. While the website runs smoothly with low data, it slows down significantly as more content is loaded. The biggest issue arises when attempting to open modals or type in text areas, with ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

Concealed/Revealed buttons linked to a tally

My website features a counter along with two buttons named button1 and button2. My goal is for button1 to be displayed while button2 remains hidden (invisible and disabled) when the counter equals 1. Conversely, I want button2 to become visible and button1 ...

The initialization of isotope must occur before calling any methods; an attempt was made to call the 'reLayout' method in angularjs prior to initialization

Implementing a gallery view using isotope and prettyPhoto in conjunction with angular js. However, encountering the issue of not being able to call methods on isotope prior to initialization; specifically getting the error 'cannot call method 're ...

Generating Multilayered PDF files with JavaScript in NodeJS

After reviewing the documentation for PDFMake, PDFKit, and WPS: PostScript for the Web, I couldn't find any information beyond background layers. It seems like Optional Content Groups might be what I need, but I'm unsure how to handle them using ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

What strategies can be employed to reduce the need for numerous if-else statements in my JavaScript code?

In my input form, users have the ability to make edits. I need to send only the data that has been changed by the user. Currently, I am repeating the same lines of code multiple times to compare and determine what data needs to be sent. Is there a more e ...