When a button is clicked within ng-repeat, the alert displays an incorrect value

Greetings! Check out my code below for displaying XML data in an HTML table using AngularJS. Each record includes a "Delete Request" button.

Here is the HTML code:

<div ng-app="myApp" ng-controller="myCtrl">
            <table border="1" width="100%">
                <tr>
                    <th>Employee ID</th>
                    <th>Employee Name</th>
                    <th>Email ID</th>
                    <th>Device Status</th>
                </tr>
                <tr ng-repeat="detail in details" align="center">
                    <td>{{detail.EmployeeID}}</td>
                    <td>{{detail.EmployeeName}}</td>
                    <td>{{detail.EmailID}}</td>
                    <td>
                        <button ng-click="getID()" class="btnDelete">Delete Request</button>
                    </td>
                </tr>
            </table>
        </div>

View the XML data displayed in the HTML table:

<UserDetail>
  <Detail>
    <EmployeeID>124578</EmployeeID>
    <EmployeeName>suresh</EmployeeName>
    <EmailID><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e1d1b1c0b1d062e161714400d0103">[email protected]</a></EmailID>
  </Detail>
  <Detail>
    <EmployeeID>587458</EmployeeID>
    <EmployeeName>Vivek</EmployeeName>
    <EmailID><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e58444f47406e565754004d4143">[email protected]</a></EmailID>
  </Detail>
</UserDetail>

Review the AngularJS code:

<script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http.get('myDB.xml')
            .then(function (response) {
                var x2js = new X2JS();
                $scope.details = [];
                var data = x2js.xml_str2json(response.data);
                $scope.details = data.UserDetail.Detail;
                $scope.getID = function () {
                    var myID = $(".btnDelete").closest('tr').children('td').eq(0).text();
                    alert(myID);
                }
            });

        });
      </script>

I am currently facing an issue where clicking on the "Delete Request" button only displays the first record's Employee ID in the alert, regardless of which button I click. Any suggestions on how to rectify this and display the corresponding record value in the alert?

Answer №1

To retrieve the employee ID, simply pass it as a parameter in the getID(detail.EmployeeID) function instead of using jQuery selectors.

HTML

<button ng-click="getID(detail.EmployeeID)" class="btnDelete">Delete Employee</button>

JavaScript

 $scope.getID = function(myID) {
   console.log(myID); // access the current employee ID when clicked
 }

VIEW DEMO

Answer №2

Avoid following this method as AngularJS emphasizes focusing on the model.

While Balachandran's answer may suit your needs, it is recommended to use that approach. However, if you still wish to proceed, you can include the following code snippet:

<button ng-click="getID($event)" class="btnDelete">Delete Request</button>

In your controller function, retrieve the reference of the button using the following code:

$scope.getID = function ($event) {
    var elmRef=$event.target;
    var myID = $(elmRef).closest('tr').children('td').eq(0).text();
}

Although I have not tested it, I believe this should work correctly.

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

When transitioning from component to page, the HTTP request fails to execute

I have created a dashboard with a component called userInfo on the homepage. This component maps through all users and displays their information. Each user has a display button next to them, which leads to the userDisplay page where the selected user&apos ...

What are some methods to identify the cause of a click not registering?

While browsing through the page, I noticed a link that looks like this: <a href="/go/some/where.htm">...</a> This link is situated within a google.maps.InfoWindow box that appears when a user hovers over a map pin. Oddly enough, when a user t ...

Using *ngFor to iterate through a nested collection in an Angular 2 application

I'm currently working on a challenge involving drilling down to iterate over an array within another collection of arrays within an Angular 2 application. To start off, I have set up my component to subscribe to an observable in the ngOnInit lifecycle ...

Load images and audio files using jQuery AJAX prior to the page being rendered

Recently, I embarked on a new project - a web app that incorporates numerous images and mp3 sounds. However, I encountered an issue where new images and sounds would load over time as users explored different parts of the app. To address this problem, I de ...

Unable to transform SVG files in Next.js Jest version 28

Currently, my setup involves Next.js version 12.0.7, Jest version 28.1.0, and the use of the next-react-svg library for importing SVG files into components. The configuration in my jest.config.js file looks like this: // jest.config.js const nextJest = re ...

How can CSS be utilized to customize a data table by removing borders and adjusting the height of data cells?

Struggling with custom styling a Vuetify data table to remove borders and adjust cell height? Check out this CodePen example. new Vue({ el: '#app', data() { return { headers: [{ text: 'Dessert (100g serving)', ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Is there a way to automatically generate additional text fields based on the user's input?

Is there a way to dynamically add multiple text fields for color and choose design based on user input? For instance, if the user enters 5 in the quantity field, how can I replicate the color and choose design fields 5 times? Additionally, how should I st ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

What if I am fine with receiving the error message 'Cannot read property **** of undefined'?

Here is some code that I am working with: $scope.query.toLowerCase() != 1 When the query is not defined, an error appears in the console. Surprisingly, the code still functions as intended despite this error. What is the best way to handle this situatio ...

AngularJS presents an error: [ng:areq] The argument 'myAppCtrl' is not recognized as a function, as it returns undefined while implementing routes with ngRoute and $routeProvider

Can anyone assist me with an error I'm encountering while setting routes on two buttons? Despite having everything properly defined, the table is not displaying any data. Your insights would be greatly appreciated. Thank you for your help. Snippet f ...

Is there a way to trigger the activation of the datepicker during the `onLoad` event?

For my project, I am utilizing this datepicker. While I am familiar with using scripts to handle changes in the date value, I am unsure of how to implement it on page load. $('.date_set .date').datepicker({ startView : 0, ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Is there a way to stop the YAML parser from including question marks in its output?

Looking to create a basic docker compose setup and integrate it into an existing file. The yaml parser found here seems promising, but I'm struggling with the question mark that appears in its output. This is the content of my current docker compose ...

Delete empty value key pairs from JSON data using JavaScript

{ "top": [{ "language": "English", "value": "" }, { "language": "German", "value": "hASTA" }], "bottom": [{ "language" ...

"Enhancing Angular 2 with a robust HTTP retry system

My API uses token-based authentication for security. Once a user successfully signs in, two tokens (access and refresh) are stored in the browser's local storage. The access token contains all the necessary information for server-side authorization an ...

Tips for importing a .ts file into another .ts file within an Angular 5 application

I have a bunch of utility methods stored in a file called utils.ts that I want to reuse across multiple components. I'm not sure if it's even possible, and if it is, where should I place the import statement and what would be the correct syntax. ...

Master the art of zeroing in on your drawing once it's complete

Please review the Demo and provide instructions on how to enhance the zoom function for Google Maps after the map is drawn. let map; let drawingManager; $(document).ready(function () { const latlng = new google.maps.LatLng(49.241943, -122.889318); ...

Mock needed assistance

In my testing scenario, I am attempting to simulate a service that is utilized by my function using sinon. However, I am encountering difficulties in inserting the mock into my function. The service is obtained through the use of require The structure of ...

Shut down all bootstrap modals

Is there a more efficient way to close all modals in my project without having to specify the ID of each one individually? Currently, I am using the following code: closeModals() { $('#new-user').modal('hide'); $('#new-pro ...