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

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

Achieving Vertical Centering of Text in Bootstrap 5 Buttons with Flex Box to Prevent Overlapping Icons

How can I prevent the text on a Bootstrap 5 button with horizontally and vertically centered text, along with a right aligned icon, from overlapping when it wraps? Additionally, how do I ensure that the icon stays vertically centered when the button text w ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

How to switch images with a click using AngularJS

When I try to toggle an image on click, I am facing an issue where clicking on one element also changes the image for another element. I'm struggling to find a solution for this situation. Here is my HTML code: <div id="TestContainer" class="Test ...

What is the easiest way to locate the ID of an iframe embedded within a webpage?

Currently, I am focused on developing small JavaScript/HTML5 ads for a webpage. Each advertisement comes with its own iframe that occupies a specific size and space on the page. In order to accommodate an expandable ad that needs to surpass the predetermin ...

Converting a JSONArray object into jQuery format

Within my Java code, there exists a JSONArray object labeled colorList that stores a collection of different colors. For example, the array may be constructed like so: ["Red", "Yellow", "Blue"] I am seeking guidance on how to transfer this information ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

Sort the currency column in an HTML table through JavaScript

I have a code snippet below that I'm currently utilizing to arrange columns in an HTML table. The code works perfectly for alphabetical sorting and also for single-digit numbers. However, when attempting to sort a column containing currency values, t ...

Can we ensure that the function is called when a node is located?

Presently, I am executing the following code but it is causing the call stack to slow down; how can I optimize this using either an async await or more advanced promise functions? I have a dynamic node that is added to the DOM at different times dependin ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

Exploring the integration of Angular JS with data retrieved from WP-API

Currently, my website is able to retrieve data from a URL using wp-api: http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=midlands When displayed using a Chrome plugin, the output looks like this - https://i.sstatic.net/ ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Error: Unable to access the 'questionText' property as it is undefined

I encountered an error message stating that my "questionText" could not be read or is not defined. The issue seems to arise in the first code block where I use "questionText", while the intention is to drag it in the second code block. Is there a mistake ...

What is causing my JS/JQuery code to only function in the console of a web browser?

I am having trouble with the $(element).scroll(function(){}); function. When I put it into a js file, it does not work properly, but when I enter it directly into the console (just the scroll func), it works fine. My goal is to implement scrolling paginat ...

Selecting options in table is disrupted by filtering in ng-repeat

My table showcases selectable information, featuring parent rows and child rows. I am seeking a solution where only the parent rows are selectable if they have no children; otherwise, only the child rows should be clickable. Essentially, it's a selec ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...

Angularfire social sign in with Facebook friends connections

When utilizing Facebook authentication with angularFire, I have encountered an issue where the "user_friends" object is not present in the Auth object that gets returned. Upon inspecting the code, it seems the ng-click directive used is as follows: "auth. ...

Disabling Commands using Discord JS Commando in a guild

Curious about something. Will Discord JS Commando disable a command only within a specific server (guild) or globally across all servers? ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...