Show the outcome of a function inside an ng-repeat loop

I have encountered a roadblock in my Angular project. I am populating a table with run data retrieved from a REST call using ng-repeat. Each run includes GPS coordinates, and I have a function that converts these coordinates into the corresponding city name. Instead of displaying the coordinates, I want the table to show the city name for each run. Currently, I have a button that triggers the function to display the city, but I want this result to be automatically shown upon loading. Can anyone offer assistance?

Below is my current code snippet:

$http.get('/fastrada/getRun.do').success(function (data) {
        $scope.runs = data;

        angular.forEach($scope.runs, function (run){
            /*run.city =*/ $scope.getInfo(run);
        });

        $scope.loading=true;
    });

$scope.getInfo = function(run)
        {
            var latlng =  run.latitude+","+run.longitude;
            var request = new XMLHttpRequest();

            if(run.latitude != 0 && run.longitude != 0) {
                request.open('GET', 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng, true);

                request.onload = function () {
                    if (request.status == 200 || request.status == 0) {
                        // Success!
                        var data = JSON.parse(request.responseText);

                        if(data !== undefined && data.results[0] !== undefined){
                            run.city = data.results[0].address_components[2].long_name;
                        }else {
                            run.city = "undefined";
                        }
                    }
                    else {
                        // Error handling
                    }
                };

                request.onerror = function () {
                    // Connection error handling
                };

                request.send();
            }else{
                run.city = "undefined";
            }
        }

And the HTML:

<tr ng-repeat="run in runs track by $index">
                                    <td>{{run.city}}</a></td>
                                    <td>{{run.getTime}}</td>
                                    <td><button ng-click="getInfo(run)">Get City</button></td>
                                </tr>

Here is a Plunk that illustrates my issue. Thank you!

Answer №1

If you want to streamline the process, consider implementing a separate controller for each Run within the ng-repeat loop. By doing so, you can initiate the lookup directly in the specific RunController instance rather than relying on a button and getInfo() method in the parent controller.

To see how this modification works, check out the updated Plunk here.

Here is an example of the new RunController setup:

fastradaApp.controller('RunController', ['$scope', '$http', '$log',
  function($scope, $http, $log) {
    $scope.loading = false;
    $scope.getInfo = function() {  
      console.log($scope.run);
      if ($scope.run !== undefined) {
        var latlng = $scope.run.latitude + "," + $scope.run.longitude;
        if ($scope.run.latitude !== 0 && $scope.run.longitude !== 0) {
          $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng)
            .success(function(data, status, headers, config) {
              $log.info(data);

              if (data !== undefined && data.results[0] !== undefined) {
                $scope.run.city = data.results[0].address_components[2].long_name;
              } else {
                $scope.run.city = "undefined";
              }
            })
            .error(function(data, status, headers, config) {
              $scope.run.city = "undefined";
            });
        } else {
          $scope.run.city = "undefined";
        }
      }

    };
    $scope.getInfo();
  }
]);

In this implementation, no "run" parameter is necessary for the getInfo() function. Instead, it utilizes $scope.run, which represents the individual run generated by the ng-repeat loop.

Additionally, I simplified the request code with a direct $http call for a cleaner approach. The revised setup eliminates the need for JSON.parse() on the results.

To enhance visibility, logging through the $log service has been included. While not mandatory for functionality, it serves as a helpful tool.

The HTML structure remains unchanged:

<tr ng-repeat="run in runs" ng-controller="RunController">
    <td>{{run.runId}}</td>
    <td>{{run.city}}</td>
    <td>{{run.time}}</td>
</tr>

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

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

Transform the appearance of several elements using querySelectorAll

When targeting class names in an HTML page with a checkbox using querySelectorAll, keep in mind that getElementByID only works with the first element. QuerySelectorAll displays a nodeList which might require some corrections - how can this be achieved? le ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Transmit information to an AngularJS application instantly

Looking for a solution to keep my AngularJS app displaying real-time data without constantly querying my api. Is there a way to establish a connection between my server and the AngularJS app so that new data can be pushed from the server to the app for dis ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

A guide on replacing certain characters with spaces using AngularJS

I'm struggling with replacing special characters in a name (Inka -Tiitto-s-Camp-Aero-Gravity-Milan-9) with hyphens (-) due to an error message that says, "The URI you submitted has disallowed characters." Additionally, the name appears as (Inka Tiitto ...

The functionality of Javascript is being compromised when utilizing ng-repeat

Just recently diving into the world of AngularJs while developing a website. I've successfully retrieved data from Rest services on a page, and used ng-repeat to display it. The issue arises when I have a regular javascript element on the page that i ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Using NPM imports within a Node-RED node: A step-by-step guide

Is there a way to utilize NPM for handling dependencies in a Node-RED node instead of embedding the files directly into the packaged node? How can I set up a node so that it can leverage NPM to fetch package dependencies? ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

data not populating in datagrid upon first load

I'm facing an issue where the data I'm trying to fetch using an API is not initially loading in my datagrid. I can retrieve the data successfully, but for some reason, it doesn't show up in the datagrid. The setup involves a common function ...

How can you customize the output buffer size (known as highWaterMark) for child_process.spawn() in node.js?

I'm currently working on adjusting the buffer size (highWaterMark) for the stdout coming from a child_process.spawn() function, but I'm encountering difficulties in achieving this successfully. The code snippet provided below demonstrates my obje ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

What is the best way to include data with a file when making an HTTP POST request with AngularJS and ExpressJS?

Situation I recently added file uploading functionality to my project. The front-end code was sourced from a popular tutorial on tutorialspoint. I am using the following service to send a POST request: myApp.service('fileUpload', ['$http&ap ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...