Navigating to an API endpoint while iterating through an ng-repeat loop

I am currently working with an API that provides a list of values. My goal is to enable users to click on the name of a driver in the API and be directed to specific details related to that driver. However, I am struggling to figure out how to implement this functionality.

Here is the current layout: https://i.sstatic.net/kv8RX.png

An alternative design: https://i.sstatic.net/tQcTo.png

Desired outcome when clicking on the driver's name retrieved from ng-repeat in the API: https://i.sstatic.net/hXJsQ.png

I am relatively new to Angular and finding it quite perplexing at the moment.

Below is an excerpt from my controller:

import { app } from '../index';

app.controller("api", function ($scope, $http) {
$scope.Naziv = "Driver Championship Standings - 2013";
$scope.NazivH1 = "Driver Championship";
$scope.TopDrivers = function () {
    console.log("Button pressed");
    $http.get("https://ergast.com/api/f1/2013/driverStandings.json")
        .then(function successCallback(response) {
            $scope.drivers = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
            console.log("response.data.MRData.StandingsTable.StandingsLists.0.DriverStandings");
            console.log(response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings);
        }, function errorCallback(response) {
            console.log("Unable to perform get request");
        });
}

Routing configuration:

app.config(function($routeProvider, $locationProvider) {
    $locationProvider.hashPrefix("!");
    $routeProvider
        .when("/drivers", {
            templateUrl: "./src/pageDetails/drivers.html",
        })
        .when("/teams", {
            templateUrl: "./src/pageDetails/teams.html",
        })
        .when("/races", {
            templateUrl: "./src/pageDetails/races.html",
        })
        .otherwise({
            redirect: "./src/pageDetails/default.html",
        });
});

Here is a snippet of my template:

<div ng-controller="api" ng-init="TopDrivers()">
    <h1>{{NazivH1}}</h1>
    <div id="modifyDiv">{{Naziv}}</div>
    <div ng-repeat="x in drivers | orderBy: '+Points'">
        <div id="divRow">
            <table>
                <tr id="tableRow"><td id="td1">Nb: {{x.position}}</td><td id="td2">{{x.Constructors[0].nationality}} {{x.Driver.givenName}} {{x.Driver.familyName}}</td><td id="td3">{{x.Constructors[0].name}}</td> <td id="td4">Points: {{x.points}}</td> </tr>
            </table>
        </div>
    </div>
</div>

Answer №1

Why have ng-repeat on div instead of <tr>? Do you want a separate div for each driver or a separate row? Consider using ng-repeat on <tr> and add a ng-click directive on your <tr>. This way, when someone clicks on a driver row, a function in your controller can be executed to route to the driver details as shown below:

<tr ng-repeat="x in drivers | orderBy: '+Points'" ng-click="driverDetails(x.DriverId)" id="tableRow">
    <td id="td1">Nb: {{x.position}}</td>
    <td id="td2">{{x.Constructors[0].nationality}} {{x.Driver.givenName}} {{x.Driver.familyName}}</td> 
    <td id="td3">{{x.Constructors[0].name}}</td>
    <td id="td4">Points{{x.points}}</td>
</tr>

In your controller, define the driverDetails function like this:

$scope.driverDetails = function (driverId) {

    $location.path('/driverDetails').search({ driverId: driverId });
};

This function will change the URL by appending the driverId as a query string. Update your routes with a new route for /driverDetails:

.when("/driverDetails", {
    templateUrl: "./src/pageDetails/driverdetails.html",
})

When the driverDetails function runs, the driverdetails.html is loaded, allowing you to retrieve the driverId from the query string. In the driverdetails controller, fetch the specific driver data from your API.

Answer №2

To create a driver details route with an optional parameter, define something like /driver-detail/:id in the route definition. Be sure to assign it its own controller and set up a method to retrieve the detailed data (consider using a service for this). Additionally, add an ng-click event handler for when a user is in the drivers list ng-repeat and click on a specific driver.

For example:

<tr id="tableRow" ng-click="goToDetail(x.id)">...</tr>

In the controller:

$scope.goToDetail() = function(id) {
    $location.path('/driver-detail/' + id)
}

Your route definition could be structured like this:

.when('/driver-detail/:id', {
    templateUrl: '...',
    controller: function($scope, $stateParams) {
      $scope.id = $stateParams.id;
      ...
    }
  }

Consider updating your technology stack as well. Even within AngularJS, the component API and tools like ui-router offer more flexibility and robust functionality compared to ngRouter. If you're kicking off a new project, consider starting with Angular CLI (currently Angular 7) for better support, resources, and development practices.

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

Creating a flowchart of a finite state machine within a browser-based software platform

If you're curious about the core logic behind my application, check out this link for a great explanation: Code Golf: Finite-state machine! I plan to implement this logic to create finite state machines on my web app using a library. I've been ...

"Step-by-step guide: Implementing a fixed scroll sidebar in AngularJS to mimic Facebook's sidebar (

As a newcomer to AngularJS, I've encountered challenges and invested a considerable amount of time trying to create a fixed right side directory. Here are the key features of the fixed scroll directory: 1) If the sidebar (whether on the Right or Left ...

Schema Connections in Kendo Diagram

I am currently experimenting with the Telerik Kendo diagram in an attempt to create a visual representation. Due to the fact that I am retrieving all shapes and their connections from my database, I encountered an issue where the attributes of my data sour ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...

The attribute 'set' is not found on the Set data type

An error message popped up saying: TS2339: Property 'set' does not exist on type Set<> Below is the code snippet that triggered the error: const id = 123; const a: Map<string, Set<File>> = new Map(); if (a.has(id)) { a.set ...

Strategies for adding elements to a FormArray in Angular 4

I am currently working on a dynamic Angular form that displays like this. <form [formGroup]="myForm"> <div *ngFor="let Repo of Repos;"> <fieldset> <legend>{{Repo.name}}</legend> ...

Should I opt for the spread operator [...] or Array.from in Typescript?

After exploring TypeScript, I encountered an issue while creating a shorthand for querySelectorAll() export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null { return [...parent.querySelectorAll(DOMElement)]; } ...

How can I implement a button in Angular Ag Grid to delete a row in a cell render

I have included a button within a cell that I want to function as a row deleter. Upon clicking, it should remove the respective row of data and update the grid accordingly. Check out the recreation here:https://stackblitz.com/edit/row-delete-angular-btn-c ...

Tips for managing various potential return types in TypeScript?

In my research on the topic, I came across a discussion thread about obtaining the local IP address in Node.js at Get local IP address in Node.js. In that thread, there is a code snippet that I would like to incorporate: import net from 'net'; c ...

Upcoming Authentication Update: Enhancing User Profile with Additional Data Points

I recently encountered an issue with my typescript application that uses Next Auth v4 along with GithubProvider and MongoDBAdapter. I needed to add a new field called role to the User schema. Researching online, most solutions suggested adding a function ...

What is preventing me from defining the widget as the key (using keyof) to limit the type?

My expectations: In the given scenario, I believe that the C component should have an error. This is because I have set the widget attribute to "Input", which only allows the constrained key "a" of type F. Therefore, setting the value for property "b" sho ...

Using a .NET Web-API controller variable as a parameter in a JavaScript function

I am looking to send a "variable" from the controller to a JavaScript function. The code I have implemented is as below: <div ng-controller="faqController"> <div ng-repeat="c in categories"> <h2 onclick="toggle_visibility(&apos ...

Encountering an error with Angular2 when referencing node modules

I encountered an issue when trying to use angular2 from the node_modules directory. Can anyone guide me on how to resolve this error? Is there something specific I need to include in my HTML file? I am looking for a Git repository where I can access Angu ...

I'm building an angular website and considering using Ionic to develop the corresponding mobile apps. Can you recommend the simplest approach for this integration?

I have developed a responsive website using Angular 4 with Lumen serving as the Rest API. The website functions smoothly on both desktop and mobile browsers, but I now intend to venture into developing mobile applications. What would be the most straightf ...

Rate of AngularJS Dirty Checking

Recently, I was diving into an article to gain a deeper understanding of the inner workings of angular.js. One concept that stood out to me was 'dirty checking($digest)'. I began to wonder at what frequency the watchers are actively listening f ...

Best Practices for Utilizing Bootstrap 5 Tooltip and Popover Methods in AngularJS Web Applications

Our AngularJS 1.8.2 application requires an upgrade to Bootstrap 5 in order to properly support Tooltips, Popovers, and Modals. Previously, we had been utilizing ui-bootstrap for handling popups. However, migrating from ui-bootstrap to Bootstrap 5 has prov ...

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

Unable to access ng-model values within ng-repeat loop

I'm having trouble setting ng-model values within an ng-repeat statement. When I repeat this div with an array of JSON objects, I am able to print the 'ID' value of the object in any element. However, I can't use that as the ng-model v ...

Angular/Ionic - How can I prevent my function from being called repeatedly while typing in an input field?

I am currently in the process of self-teaching how to construct an Angular/Ionic application. To store JSON, I am utilizing Backand and aiming to retrieve a random JSON value each time the page is refreshed. An issue I am facing is that the random call fu ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...