Displaying only the final item from an array when clicking in an ng-repeat loop

My objective is to display the details of each value from my data in a pop-up window. However, instead of showing three different values, the pop-up only displays the last value from an array three times.

This is the HTML code I am using:

  <div ng-repeat="value in all | filter: (!!locationFilter || undefined) && {type: locationFilter} | filter: priceFilter | filter: datesFilter | orderBy:sortProp">
                  <ul>
                     <li><img src="app/images/{{value.image}}.jpg" alt="Smiley face" height="100" width="240"></li>
                     <li><strong>{{value.id}}</strong></li>
                     <li><strong>{{value.address}}</strong></li>
                     <li>city: {{value.city}}</li>
                     <li>postcode: {{value.postcode}}</li>
                     <li>price: £{{value.price}}</li>
                     <li>num_of_beds: {{value.num_of_beds}}</li>
                     <li>{{value.type}}</li>
                     <li>{{value.minutes}}</li>
                     <li>{{value.added}}</li>
                  </ul>
                     <div ng-click="togglePopup(value)">
                     view details
                        <div class="modal-outer" ng-if="showPopup">
                           <div class="modal-container">
                           {{selectedValue.address}}
                              <div ng-repeat="subValue in value.details track by $index">
                                 <ul>
                                    <li>{{subValue.desc}}</li>
                                    <li>{{subValue.info}}</li>
                                 </ul>
                              </div>
                           </div>
                        </div>
                     </div>
               </div>

Additionally, here is the JavaScript function:

$scope.showPopup = false;
        $scope.selectedValue = {};

        $scope.togglePopup = function(value) {
           $scope.showPopup = !$scope.showPopup;
           if (value) 
            $scope.selectedValue = value;   
        };

This is the data I am working with:

"allData": {

        "patientsData": {

            "patients": [{
                "id": 1,
                "image": "amsterdam",
                "address": "17 Peregrine House",
                "city": "London",
                "postcode": "SW11 2NL",
                "price": "150.000",
                "num_of_beds": 1,
                "type": "terraced",
                "minutes": 20,
                "added": "Jan 6 2017",
                "details": [{
                    "desc": "Beautiful terraced house looking like houses in Amsterdam",
                    "info": "dcjkbc"
                }]
            }, {
                "id": 2,
                "image": "dutch",
                "address": "22 Portland House",
                "city": "London",
                "postcode": "SW12 2SE",
                "price": "800.000",
                "num_of_beds": 3,
                "type": "detached",
                "minutes": 10,
                "added": "Dec 28 2016",
                "details": [{
                    "desc": "Dutch house in the countryside",
                    "info": "dcjkbc"
                }]
            }, {
                "id": 3,
                "image": "evy",
                "address": "2 Holland Road",
                "city": "London",
                "postcode": "SW10 2RE",
                "price": "950.000",
                "num_of_beds": 4,
                "type": "terraced",
                "minutes": 5,
                "added": "Jan 5 2017",
                "details": [{
                    "desc": "Newly decorated house",
                    "info": "dcjkbc"
                }]
            }]
          }
       }

Upon clicking on "view details" with ng-click="togglePopup(value)," the popup only displays the last value from the subarray named "details" in my JSON, causing it to be repeated three times. Any guidance on how to resolve this issue would be greatly appreciated.

Answer №1

It is recommended in the documentation to use an object's unique identifier for tracking purposes when available:

When dealing with objects that have a unique identifier property, it is advised to track by this identifier instead of the object instance. This prevents ngRepeat from needing to rebuild DOM elements for items that have already been rendered, even if the JavaScript objects in the collection have been replaced with new ones. This can greatly improve rendering performance for large collections. If a unique identifier is not available, tracking by $index can also enhance performance.

Since you have an id value, it is suggested to track by value.id like this:

<div ng-repeat="subValue in value.details track by value.id">

For more information, you can refer to the AngularJS documentation at the following link: https://docs.angularjs.org/api/ng/directive/ngRepeat

Regarding the error you mentioned, the code you provided seems to be correct. Here is a link to a working example on CodePen:

http://codepen.io/egerrard/pen/egvOaX

The issue may lie in some other code that has not been shared in this context.

Answer №2

Consider making a modification to this line:

<div ng-repeat="subValue in value.details track by $index">

by changing it to:

<div ng-repeat="subValue in all[$index].details track by $index">

It seems that value may be getting bound to the last element of your ng-repeat. By making this adjustment, you will be able to correctly select the appropriate value element from your list.

Alternative approach:

Suggesting a different approach here. Can you relocate the pop-up so that it is not nested within the ng-repeat?

<div class="modal-outer" ng-if="showPopup">
    <div class="modal-container">
        {{selectedValue.address}}
        <div ng-repeat="subValue in value.details track by $index">
            <ul>
                <li>{{selectedValue.details.desc}}</li>
                <li>{{selectedValue.details.info}}</li>
            </ul>
        </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

Enhance your React Typescript application by dynamically increasing the elements within a useState array using a string array

How can I efficiently add multiple elements to a useState array in React using a new string array? The current function I have only adds a single string, and when I loop through the string array to update the state, it only appends the last element. I ne ...

The React rendering process failed when attempting to utilize a stateless component

Struggling to integrate a stateless component with fetch in my project. The fetch API is successfully retrieving data, but for some reason, the stateless component remains blank. import React, { PropTypes } from 'react'; import { Card, CardTitle ...

Steps to retrieve the central coordinates of the displayed region on Google Maps with the Google Maps JavaScript API v3

Is there a way to retrieve the coordinates for the center of the current area being viewed on Google Maps using JavaScript and the Google Maps JavaScript API v3? Any help would be greatly appreciated. Thank you! ...

Techniques for merging two arrays with commas in PHP

Is there a way to concatenate two array values with a comma in between? Below is the code snippet: <?php $abc=array( 'Title' => 'mr', 'FirstName'=> 'fname', 'Middlename'=> &ap ...

Is it possible to create HTML content directly from a pre-rendered canvas element or input component like a textbox?

As I delve into learning JavaScript and HTML5, a couple of questions have sparked my curiosity: 1) Can we create HTML from a Canvas element(s)? For instance, imagine having a Canvas shape, and upon clicking a button, it generates the HTML5 code that displ ...

Dynamic Content Sorting with JavaScript and jQuery

I am presenting various courses that are available, and I am utilizing JavaScript/jQuery to display or hide them based on element classes. You can view the page here. Currently, the script conceals all content on the page and then reveals items that matc ...

Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

I can't figure out why my SCSS isn't loading, even though I've added it to the webpack.mix.js file in my Laravel project that's set up with React.js

I'm facing a problem where my SCSS is not loading in the VideoBackground.js component of my Laravel project built with React.js, even though I have set it up correctly in the webpack.mix.js file. The file path for the videoBackground.scss file within ...

Using switch statement upon page loading in AngularJS

I am currently working on refactoring a switch statement that identifies specific classes upon page load into one of my controllers. Does anyone have suggestions on how I can transform this straightforward task using Angular? $('.radior').eac ...

Has Jade stopped allowing inline variables unless enclosed by JavaScript markers?

Back when I was using Jade version 0.34.1 (prior to the release of version 1.0.0), I had the ability to incorporate inline variables like this: test = 'fun' p #{test} This would typically result in: <p>fun</p> However, the output ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Creating a personalized mouse cursor using HTML

I am trying to set an image as my cursor inside a div container but I want it to disappear and revert back to a normal pointer cursor when the mouse hovers over any link within that div. Here is my code snippet: var $box = $(".box"); var $myCursor = $ ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

Show that a CPU-intensive JavaScript function is executing (animated GIF spinners do not spin)

Displaying animated indicator or spinner gifs, then hiding them, is an effective way to communicate to the user that their action is being processed. This helps to assure the user that something is happening while they wait for the action to complete, espe ...

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...

The ng-app feature is causing the script to run endlessly

Currently, I am troubleshooting an issue within my angular application that is built on the asp.net web application empty template. The problem arises when I utilize ng-app; if I leave it blank, the $routeProvider fails to initialize. However, if I specify ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...