Guide: Utilizing ng-repeat in Ionic framework for displaying nested JSON objects

Currently in the process of developing a basic hybrid mobile application using the Ionic framework. The main functionality involves sending a GET request to retrieve matching last names when searched for, and then displaying their corresponding ID's. However, encountering difficulties in correctly displaying the returned data from the JSON object.

Here is snippet of the HTML page:

<ion-view view-title="Account" ng-controller="AccountCtrl">
<ion-content>
    <div class="list">
        <div class="item item-input-inset">
            <label class="item-input-wrapper">
                <input type="text" placeholder="Search" ng-model="name">
            </label>
            <button class="button button-small" ng-click="searchUser(name)">
                Go
            </button>
        </div>
    </div>
    <div>
        <ul ng-repeat="user in $results">
            <li>{{user.id}}</li>
        </ul>
    </div>
</ion-content>

And here is the JavaScript file that successfully retrieves a populated JSON object with all necessary information.

angular.module('starter.controllers', [])

.controller('AccountCtrl', ['$scope', '$http', function ($scope, $http) {

$scope.searchUser = function (name) {
    $http.get('https://notrelevantforthis/searchLastName?=' + name).then(function (response) {
        console.log(response.data)

        //Assign JSON obj to results to repeat through and display data
        $scope.results = response.data;

        //To show the actual JSON object is returned
        //var jsonStr = JSON.stringify($scope.results);
        //document.body.innerHTML = jsonStr;

    }, function (error) {
        console.log(error)
    });
};
}]);

The structure of the JSON object itself seems to be the crux of the issue. It follows this pattern:

{
"response": {
  "totalFound": 275,
  "start": 0,
  "acc": [
    {
      "id": [
        "1"
      ],
      "first_name": [
        "Joe"
      ],
      "last_name": [
        "Smith"
      ]
    },
    {
      "id": [
        "2"
      ],
      "first_name": [
        "John"
      ],
      "last_name": [
        "Doe"
      ]
   }]}
}

Struggling with iterating through the JSON object using ng-repeat. Despite seeing the object in the console, none of the data is being displayed on the page. Any guidance or assistance in identifying where the mistake lies would be highly appreciated, especially since I am new to this and still trying to figure out the correct methods.

EDIT: Attempted using collection-repeat provided by the Ionic framework but encountered stack limit errors.

Answer №1

When you assign response.data to $scope.results, you are essentially assigning the HTTP response body, which contains the JSON object from your query. To iterate through the accounts, you need to reference response.data.response.acc.

In your template, use ng-repeat="user in results" without the $.

The JSON object provides the account IDs as an array. It is recommended to provide just the literal value instead of the array so that you can directly print the value without accessing the array itself.

An example has been created for you: http://plnkr.co/edit/GYeF4FzVHl8Og5QTFcDx?p=preview

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

Interactive HTML5 Web Application File Selector

After conducting thorough research, it is important to note that I am well-versed in the security implications of this client-side application which utilizes JavaScript, Vue, and pure HTML5. To initiate the file dialog, I employ a hidden input type file. ...

Protractor - selecting a hyperlink from a list

Imagine you have a todo application with tasks listed as follows: Walk the dog, Eat lunch, Go shopping. Each task has an associated 'complete' link. If you are using Protractor, how can you click on the 'complete' link for the second t ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

The SendGrid API is organizing these tables as a team

While attempting to send an email using SendGrid, the tables in the content are being grouped together instead of displaying as intended. Despite my efforts to reformat the code, the final email appearance is not what I expected. I have diligently review ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

Is there a way to make images appear on the screen only when they come into view on

While exploring the internet, I came across something quite intriguing on a website: As you scroll down the page, images only load when they come into view in the browser window. This is a feature I have never seen before and I am curious if anyone else h ...

The Google analytics page tracking feature is experiencing issues within an AngularJS application and is not functioning correctly

My current project focuses on AngularJS, catering to both mobile applications and desktop websites. I have downloaded analytics.js locally and integrated it into my GA tracking code within the index.html file: (function(i,s,o,g,r,a,m){i['GoogleAnalyt ...

Changing NSString to NSDictionary in Objective-C

This is the unique text { UniqueModel = XYZ; DPIHeight = 144; DPIWidth = 144; Depth = 16; Orientation = 2; PixelHeight = 5696; PixelWidth = 8576; ProfileName = "XYZ Color Profile"; "{Custom}" = ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

Prevent Fixed Gridview Header from being affected by browser Scroll-bar using JQuery

Is there a way to make the fixed header responsive to only one scroll bar in JQuery? Specifically, is it possible to have it respond solely to the div's scroll bar and not the browser's scroll bar? I attempted to remove the browser's scroll ...

Extract the JSON information and determine the frequency of each data item

I am looking to extract the json data and retrieve the count for Leadstage. Specifically, I aim to obtain the leadstage count based on geographical location. { "Geo" :"US East" "LeadStage": "SGL", &quo ...

I am having issues with the drag and drop directives in AngularJS - they work fine on my computer's navigator, but they

I have successfully implemented drag and drop directives in angularJS, and they are functioning properly on my computer's web browser. However, when I tried to use the directives on my touch devices, they did not work. Should I make adjustments to my ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

Insufficient Resources Error (net::ERR_INSUFFICIENT_RESOURCES) encountered while executing jQuery script with multiple ajax requests for 2 minutes

Upon initially loading the code below, everything seems to be functioning smoothly with the dayofweek and hourofday functions. However, shortly thereafter, the browser (Chrome) freezes up and displays the error message: net::ERR_INSUFFICIENT_RESOURCES. Thi ...

The 'in' operator cannot be utilized to search for '_id' within

I am attempting to retrieve an existing user document using mongoose with express, but I am encountering the following error: /webroot/api.domain.com/production/node_modules/mongoose/lib/document.js:162 if (obj && '_id' in obj) con ...

Error Message: AngularJS Breeze - Property 'then' cannot be accessed on an undefined or null reference

I encountered a specific exception after retrieving data from the breeze controller. TypeError: Unable to get property 'then' of undefined or null reference Here is the code snippet involved: Student.js function fetchUsers() { return re ...

Exploring various substances when combining shapes in Three.js enhances the visual appeal and complexity of

I have a vision to construct a Pine tree using 2 different meshes - one for the trunk and another for the bush. Here is what I have tried so far: var pine_geometry = new THREE.Geometry(); var pine_texture_1 = THREE.ImageUtils.loadTexture('./res/text ...

Encountered an issue when attempting to access a file on the desktop using Node.js

Here is the code I am using to read a simple file from my desktop: module.exports = function (app) { app.get('/aa', function(req, res) { fs = require('fs'); fs.readFile('‪C:\\Users\\t5678 ...

Updating the time component of a datetime object using Angular's HTTP method

I'm facing a strange bug with my API interaction through AngularJS. When trying to update something, I encounter the following code snippet: console.log('updated: ', event.startsAt); $http({ method: 'PUT', url: baseurl ...

Top guidelines for validating inherited props within React applications

Exploring a component called <Section /> which requires 3 props to function: color size title The color and size props are used for styling purposes, while the title prop is passed down to its child component <SectionTitle />. Here's an ...