Generate random users with Angular JS based on their ID using the User Generator API

I am new to using Angular and recently achieved success in making an Ajax call to the Random User Generator API to display a list of users. Now, I am aiming to create a detailed view when a user is clicked on. Within my HTML, I have implemented a function call: fetchInfoById(user.id.value). Below is the script for this function:

$scope.fetchInfoById = function(info_id) {     
   $http.get("https://randomuser.me/api/?id.value="+info_id)
   //also tried:   $http.get("https://randomuser.me/api/?id/value="+info_id)
          .success(function(data) {
            $scope.oneUserResult = data.results; 
    }); 
}

The current implementation does display a user detail view, however, it is not showing the selected user. Can anyone identify what I may be doing incorrectly?

Answer №1

Thank you for sharing your valuable suggestions. Although it's a random generator, by setting parameters such as "seed=...", the same individuals are shown in each listview request:

$http.get('https://randomuser.me/api/?results=15&seed=abc&inc=gender,name,location,email,dob,phone,cell,id,picture,info,nat&nat=gb')
    .success(function(response){
        $scope.userResult = response.results; 
});

I then extracted the id of each person and used it as a parameter in the function call for the detailed view request.

To ensure I passed the correct value for the detail view request, I even hard coded the parameter for the request like so:

$scope.getInfoById = function(info_id) {    
    console.log("from HTML: "+info_id.value );   //  =  JK 00 46 67 
    $http.get("https://randomuser.me/api/?id="+'JK 00 46 67 H')    ...             

The JSON data within the API is structured with the id-property formatted as follows:

{
  "results": [
    {
     "id": {
        "name": "BSN",
        "value": "04242023"
     },...

I am still working on finding out how to retrieve a single user by their id. Even with a hardcoded id, I keep getting different users every time... Instead of making another request, my workaround was to pass the "clicked user" as a parameter for the detailed view.

Answer №2

Update your code with the following changes:

$scope.getInfoById = function(info_id) {     
   $http.get("https://randomuser.me/api/?id="+info_id)
   //tried this as well:   $http.get("https://randomuser.me/api/?id/value="+info_id)
      .success(function(data) {
        $scope.userData = data.results; 
   }); 
}

Ensure that you are providing the correct value when calling this function.

Answer №3

Retrieve a group of individuals from the API call "".

$scope.getAllUsers= function(resultCount) {     
       $http.get("https://randomuser.me/api/?results="+resultCount)
            .success(function(data) {
            $scope.users= data.results; 
   }); 

Show them on the display.

When one entry is clicked, fetch details for that specific individual from the previously fetched list of users.

$scope.getUserById= function(userId) {
    return $scope.users.filter(function(user) {
      return user.id.value=== userId;
    })[0]; // make sure to include necessary null / undefined checks when needed.
  }

Answer №4

Here is an alternative method with ng-model:

$scope.person = {};
$scope.retrieveDataById = function() {     
   $http.get("https://exampleapi.com/userinfo?id="$scope.person.id)
      .success(function(info) {
        $scope.singleResult = info.details; 
   }); 
}

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

Sending a JavaScript variable to another JavaScript file and ultimately to a Django view

I have a collection of cards featuring various items. Each card includes a counter and an 'Add to Cart' button. I am looking to send the item count to a Django view using Ajax. However, I am unsure how to pass the counter variable to the Ajax fun ...

How do I specify a unique directory for pages in Next.js that is not within the src or root folders?

I'm currently facing an issue when trying to set a custom directory in Next JS. Although the default setup dictates that the pages directory should be located at the root or within the src directory, this arrangement doesn't fit my requirements ...

retrieveValue() for SelectionDropdown

I have a simple task - I just need to retrieve the name of the Company and store it in the database. Initially, I was able to achieve this using plain text and the code snippet below: sport: this.refs.company.getValue(), which worked perfectly. However, ...

Steps for displaying an Array value in a Text input field

I have this Array array 0 => array 'id' => 1 'name' => Peter 'desc' 'date' 1 => array 'id' 'name' 'desc' ...

The collapsed button on the Bootstrap 4 accordion flickers slightly as it expands, not reaching its full expansion

I'm currently working on implementing an accordion feature. I found inspiration from this component here on fiddle which utilizes bootstrap 4. While attempting to troubleshoot a bug in the SO forum, I noticed that on my page, the component seems to "b ...

Utilizing d3.js to implement a scatterplot with zoom functionality that focuses solely on zooming the axis without affecting

Having trouble creating a scatterplot with zoom functionality where only the axis is getting zoomed, not the data itself. Can anyone provide some assistance or insight on what might be wrong? If you're interested in checking out the project, here&apo ...

Changing array element to undefined within an else if statement

I'm facing a puzzling issue while developing a web application in Node.js. The app is supposed to parse .csv files and insert them into a MySQL database. The problem arises at a particular point within the function: var router = require('express ...

Is there a more efficient method to achieve the desired effect without making multiple calls to jQuery ajaxSuccess?

Currently, I am working on creating an effect that involves a quick fade-out followed by a fade-in of the element once the request is successful. Since jQuery processes elements in a routine manner (top to bottom), I have managed to achieve my desired eff ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

How come HTML fails to display an image sent through Express?

I have a remote server with an Express server that serves a tiger image at this link. The Express server code on the link is: var express = require('express'); var app = express(); app.use(cookieParser()) app.use(cors()) app.use(helmet()) app.us ...

Configuring a custom domain for a Rust service on Clever Cloud: A step-by-step guide

After successfully deploying my Rust service to the Clever Cloud platform and testing it on PROD and localhost, I am now facing the challenge of binding my custom domain with the deployed service. I would like to eliminate the need for using the lengthy C ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

proceeding to an external webpage | angular

I am working on securing an angular app that is part of our organization's system. Our central SSO app handles logins and sets cookies once a user is authenticated. My main challenge now is figuring out how to redirect users from my angular app to th ...

Using $watch to track changes in a class when a directive fires one cycle later

My ultimate aim is to trigger an action when a specific directive receives the class 'focused' through ng-class. However, closely monitoring changes on each of the directives is resulting in some unexpected outcomes that puzzle me. Below is the i ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

The Ajax URL is failing to connect with the controller through IIS

I am facing an issue where the application gets stuck in the Home controller when running it on IIS. It doesn't progress to the next controller (Data controller) as specified in the URL. However, when I run it in debug mode, everything works fine. How ...

Error encountered at the conclusion of input within a search button segment

I am currently in the process of developing a webpage that accepts a string input and then utilizes the Wikimedia API to search Wikipedia for 10 relevant pages. The issue I am facing lies within my JavaScript success function, where I intend to populate a ...

Tips for CSS: Preventing onhover animation from resetting with each hover

I've created an on-hover CSS animation that smoothly transitions between images. However, I encountered a lagging issue when the user quickly hovers over SECTION ONE and SECTION TWO before the animation ends, causing the animation to restart and lag. ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...