Exploring the contrasts in values within the ng-repeat directive of AngularJS

I am currently working with a JSON object that contains information about various clients, including the payments made over different date ranges within each month. My goal is to loop through this list of customers and display a table for each customer, highlighting any variations in payments between periods. However, I am facing difficulty comparing the payment made at the end of one month with the payment made at the beginning of the next month.

The JSON data from the legacy system looks like this:

{  
 "customers":[  
    {  
     "name":"John",
     "months":{  
        "1":{  
           "details":[  
              {  
                 "startDate":1483225200000,
                 "endDate":1483830000000,
                 "payment":250
              },
              {  
                 "startDate":1483916400000,
                 "endDate":1485817200000,
                 "payment":350
              }
           ]
        },
        ...
     }
  },
  ...
 ]
}

Below is my HTML code where I use ng-repeat to iterate over the data and apply the "highlight" class when payments vary:

<table ng-repeat="customer in customersList">
<tbody ng-repeat="month in customer.months">
    <tr ng-repeat="detail in customer.details track by $index">
        <td data-ng-class="{'highlight' : month.details[$index-1].payment != month.details[$index].payment && $index > 0}">{{::detail.payment}}</td>
        <td data-ng-class="{'highlight' : month.details[$index-1].payment != month.details[$index].payment && $index > 0}">{{::detail.payment | currency}}</td>
    </tr>
</tbody>
</table>

Although I attempted to use $parent to access previous month data for comparison, I encountered difficulties in achieving the desired outcome. I would appreciate any insights on what might be causing this issue and whether it is feasible to compare payments across months in this manner.

Answer №1

The reason why your current implementation is not working is because the $index refers to the index in month.details instead of customer.months.

This is where the use of the ng-init directive can be helpful.

If I understand correctly, you are trying to compare payments. You may want to try something like this:

<table ng-repeat="customer in customersList">
<tbody ng-repeat="month in customer.months">
    <tr ng-init="monthIndex = $index" ng-repeat="detail in customer.details track by $index">
        <td data-ng-class="{'highlight' : customer.months[monthIndex - 1].details[$index].payment != month.details[$index].payment && monthIndex > 0}">
            {{::detail.payment}} {{customers.months[monthIndex - 1].details[$index] != month.details[$index].payment && $index > 0}}
        </td>
        <td data-ng-class="{'highlight' : customer.months[monthIndex - 1].details[$index-1].payment != month.details[$index].payment && monthIndex > 0}">
            {{::detail.payment | currency}} {{customers.months[monthIndex - 1].details[$index].payment}}
        </td>
    </tr>
</tbody>
</table>

By setting monthIndex as the index of the current month before entering the month.details loop, you can refer back to the previous month within the month.details loop using monthIndex - 1.

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

Tips for making Ajax crawlable with jQuery

I want to create a crawlable AJAX feature using jQuery. I previously used jQuery Ajax on my website for searching, but nothing was indexed. Here is my new approach: <a href="www.example.com/page1" id="linkA">page 1</a> I display the results ...

Understanding JSON Dates

At this point, I find myself a bit puzzled with what I'm currently observing. To elaborate, the scenario involves me converting a MongoDate to JSON by utilizing PHP's json_encode function along with MongoDB functionalities. The resulting output c ...

Tips for clearing input fields in React.js without using an empty string

Is there a way to reset the input field in this specific scenario? const [username, setUsername] = useState({ username: "", usernameError: "" }); const handleUsername = (inputUsername) => { if (inputUsername.length > ...

Shuffling Numbers in an Array After Removing an Element with AngularJS

I am working with a JSON array that contains tasks: tasks = [{taskcode:1, taskName:'abc'}, {taskcode:2, taskName:'abc1'}, {taskcode:3, taskName:'abc2'}, ..... ]; If I delete a task with the nam ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Moving from the landing page to a specific tab in Ionic 2+ using dynamic navigation

Upon launching the application, users are greeted with a landing page called IntroPage, featuring two prominent buttons labeled BUY and SELL. Clicking on either of these buttons will navigate users to the corresponding buy or sell Tab. In my quest to achi ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...

The SharedArrayBuffer does not exist in this context

A new library, react-canvas, has been causing some trouble for me. Lately, an error message keeps appearing with the <p> tag in the canvas area where it should be displayed on browsers like Chrome. The framework I'm using is nextjs, and I&apos ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

Guidelines for creating a dynamic filter in Prisma js

I am looking to create a dynamic filter based on user input from the frontend. On mapping the data, I found that the object results appear like this: { id: '2', name: 'yuhu' } The keys 'id' and 'name' need to be dyn ...

Using the JavaScript selectionchange event to target a specific element exclusively

I am looking for a way to incorporate a JavaScript selectionchange event on a specific div element. The goal is to display a highlighter box when the user selects text from the DOM. I was able to achieve this functionality for web using an onmouseup event, ...

The functionality of the Datepicker popup box is slightly affected by Angular's $compile method

UPDATE 1: additional details have been included. UPDATE 2: the plunker code has been added to replicate the issue. Refer to the link provided below. UPDATE 3: I received a response from the Angular team on github. You can view it here. UPDATE 4: An u ...

Uh-oh! Trouble loading web app dependencies: 404 Error

Currently, I have a functional SailsJS boilerplate application. The next step I am trying to undertake involves integrating Angular-Material as a dependency in order to kickstart some UI development tasks. However... After installing angular-material usin ...

Stop form from submitting on bootstrap input, still check for valid input

Encountering a dilemma here: Employing bootstrap form for user input and utilizing jQuery's preventDefault() to halt the form submission process (relying on AJAX instead). Yet, this approach hinders the input validation functionality provided by boots ...

Exploring the differences in JSON string comparison utilizing openjson within SQL Server 2016

There are two cases where I need to insert a JSON string. I first check if the JSON string already exists using the code below, then proceed with the insertion into the table. **Case - 1** declare @jsonStr nvarchar(max) = {"Manufacurer": "test", "Model" ...

Use of ng-if in combination with recursive directives does unexpected behavior

I have a situation where I am using two recursive directives inside ui-bootstrap tabs. In order to optimize performance, I want the directive to only load when its corresponding tab is active. To achieve this, I am using ng-if on the directive like this: & ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...

Creating a single loop in Javascript to populate two dropdown menus with options

Is there a way to populate two dropdown menus in JavaScript with numbers using the same for loop? Currently, only one is being populated, specifically the last one. for (var i=1; i<10; i++) { var option = document.createElement("option"); option. ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...