JSON object fails to iterate with ng-repeat

It must be the scorching temperature...

Having a json object that I'm eager to loop through using ng-repeat, it should be straightforward, but alas! it's just not cooperating.

Here's the HTML snippet:

<a data-ng-repeat="x in template.menuObj" href="{{ x.link }}">{{ x.name }}</a>

JSON Data:

[
    {
        "ACL":{
            "*":{
                "read":true
            }
        },
        "link":"home",
        "menu":"main",
        "name":"Home",
        "order":1,
        "objectId":"aDcb0HUXwB",
        "createdAt":"2015-08-05T15:29:05.948Z",
        "updatedAt":"2015-08-05T15:29:11.915Z"
    },
    {
        "ACL":{
            "*":{
                "read":true
            }
        },
        "link":"category/the-interesting-stuff",
        "menu":"main",
        "name":"The Interesting Stuff",
        "order":2,
        "objectId":"znXfUF0kdJ",
        "createdAt":"2015-08-05T15:33:11.332Z",
        "updatedAt":"2015-08-05T15:33:39.738Z"
    },
    {
        ...
]

Running this results in 5 empty <a> elements like this:

<a data-ng-repeat="x in template.menuObj" href="" class="ng-binding ng-scope"></a>

Seems like Angular recognizes the 5 arrays, but for some reason, the keys aren't being captured?

EDIT: The creation of the JSON object looks something like this (using parse.com):

var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
    console.log(JSON.stringify(results));
    $scope.template.menuObj = results;
}, function(error){
    // error-handling
    console.log("Error: " + error.code + " " + error.message);
});

EDIT EDIT: Controller details:

blogApp.controller('templateCtrl', function($scope, templateService) {
    $scope.template = templateService;

    var Menu = Parse.Object.extend('Menu');
    var query = new Parse.Query(Menu);
    query.ascending('order');
    query.equalTo('menu', 'main');
    query.find().then(function(results){
        console.log(JSON.stringify(results));
        $scope.template.menuObj = results;
    }, function(error){
        // error-handling
        console.log("Error: " + error.code + " " + error.message);
    });
});

templateService is a factory that connects to a parent controller. It's worth noting that prior to incorporating parse.com into this project, the ng-repeat functioned perfectly when fetching a json object via PHP/MySQL using $http.

EDIT EDIT EDIT: Check out the screen capture of console.log(results);

Answer №1

The issue here is that the array object is named `results` and you are assigning it to `$scope.template.menuObj` without giving it a specific name in the JSON array. You have two options:

"menuObj": [
    {
        "ACL":{
            "*":{
                "read":true
            }
        },
        "link":"home",
        "menu":"main",
        "name":"Home",
        "order":1,
        "objectId":"aDcb0HUXwB",
        "createdAt":"2015-08-05T15:29:05.948Z",
        "updatedAt":"2015-08-05T15:29:11.915Z"
    },
    // Other menu items...
]

Alternatively, you can keep the current structure but adjust the controller as follows:

blogApp.controller('templateCtrl', function($scope, templateService) {
    $scope.template = templateService;

    var Menu = Parse.Object.extend('Menu');
    var query = new Parse.Query(Menu);
    query.ascending('order');
    query.equalTo('menu', 'main');
    query.find().then(function(results){
        $scope.template = JSON.stringify(results);
    }, function(error){
        console.log("Error: " + error.code + " " + error.message);
    });
});

Update the view accordingly:

<body ng-app="blogApp">
<div ng-controller="templateCtrl" >
    <nav ng-repeat="a in template">
      <a href="{{ a.link }}">{{ a.name }}</a>
    </nav>
</div>
</body>

If you prefer to work with it as originally intended, make the following adjustments:

<body ng-app="blogApp">
<div ng-controller="templateCtrl" >
    <nav ng-repeat="a in template.menuObj">
      <a href="{{ a.get('link') }}">{{ a.get('name') }}</a>
    </nav>
</div>
</body>

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

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

Issue with integer comparison in Objective-C code causing unexpected results

Here's the issue I'm facing: I've been getting a JSON string from a network source, which, when decoded using SBJSON libraries, turns into an NSDictionary. This dictionary is supposed to contain a numerical value for the 'userid' ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

Transform a "flat" array into one that mimics a hierarchical directory structure

I am working with a collection of "directory objects" that have the following structure: $directoryObjects = [ [ 'type' => 'folder', 'name' => 'animals', 'path' => &apo ...

Instructions on how to invoke a function defined in a JavaScript module (type=module) from an HTML document

I've been facing difficulties with using JavaScript modules... I have an HTML file and a JS module. In the javascript file, I have a function defined that I want to call from my HTML page. Here is my code: index.html <html> <head> < ...

How come my associative array is being transformed into an object in PHP?

As I am working on creating an associative array, the following code snippet is utilized: public function getEnumFlag(){ $enums = Category::getPossibleEnumValues('flag'); $enumArray = array(); foreach($enums as $enum){ $enum ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Utilize a dynamic approach to add the active class to navigation list items

My files all have a header that includes a navigation bar. I am trying to use jQuery to add the 'active' class to the relevant list items (li). The method I initially thought of involved setting a variable on each page, assigning an ID equal to ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

What is the process of matching a server response with the appropriate pending AJAX query?

Imagine a scenario where my web app utilizes AJAX to send out query #1, and then quickly follows up with query #2 before receiving a response from the server. At this point, there are two active event handlers eagerly waiting for replies. Now, let's ...

Converting object values to strings is a common practice during JSON posting operations

I encountered an issue with a date object when sending it to a NodeJS server. While the object is still preserved, the time gets converted to a string during the process. Is there a way to prevent this conversion? I tried parsing the object but received an ...

Discovering the Vue app container div attribute

I am currently working on a Java app that generates pages server-side based on certain data, such as a publisher for a specific entity. I want to develop a reusable Vue component that can call an API method to request data about the entity that is being vi ...

How can VueJS dynamically incorporate form components within a nested v-for loop?

I've encountered a challenge while working on my project. Here is the form I'm currently using: Upon clicking the 'New Deal Section' button, a new section like this one is created: My goal is to add multiple text boxes in each sectio ...

Getting the value returned by http.request in an app.get method using express.js

When attempting to deliver data from an API on another domain using app.get, I am able to write the data to the console successfully. However, the data is not showing up on the page ('~/restresults'). This is the current code I have: app.get(&a ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

Sending JavaScript arrays to PHP via Ajax请求

I am facing a challenge in passing values from a multiple select listbox using Ajax to PHP. I have come across examples using jQuery and JSON, but I am determined to achieve this using plain JavaScript (Ajax) only. Here is a simplified version of what I ha ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...