Present intricate JSON data using only one ng-repeat in AngularJS

I am currently attempting to showcase all the books within a specific series. Initially, I utilized nested ng-repeat and achieved the desired outcome. However, with recent modifications to the layout requirements, I am no longer able to use nested ng-repeat (my goal is to have a single list of books). Ideally, it would look something like the example below:

<ul>
    <li>book 1 of series 1</li>
    <li>book 2 of series 1</li>
    <li>book 1 of series 2</li>
    <li>book 2 of series 2</li> 
    <li>book 1 of series 3</li>
    <li>book 2 of series 3</li>
</ul>

Is there a way to achieve this using only one ng-repeat? Or perhaps by employing another method like an Array?

Data

var data = {
    "records": [
        {
            "name": "Spectrum Series",
            "seriesid": "SpectrumSeries",
            "book": [
                {
                    "name": "White Curse",
                    "bookid": "WhiteCurse",
                    "image": "book1"                    
                },
                {
                    "name": "Blue Fox",
                    "bookid": "BlueFox",
                    "image": "book2"                   
                }
            ]
        }

… additional series
 ]
};

Controller

$scope.serieslist = data.records;

HTML

    <div ng-repeat="series in serieslist">
        <ul>      
            <li ng-repeat="book in series.book">                  
                <div>{{series.name}}</div>
                <div>{{book.name}}</div>                    
            </li>            
        </ul>
    </div>

Answer №1

If you're looking to display a single list of books, consider using the following code snippet:

<div ng-repeat="book in booklist">
        <li>                  
            <div>{{book.title}}</div>
            <div>{{book.author}}</div>
        </li>            
    </ul>
</div>

I hope this helps with what you're trying to achieve!

Answer №2

In order to properly display the array in your controller, you should first flatten it into an array containing series numbers and book numbers. Then, utilize the ng-repeat directive on the new array.

To achieve this, you can iterate through the original array using two angular.forEach functions - one for the series and another for the books within each series.

$scope.serieslist = [];
var seriesNumber = 1;
angular.forEach(data.records, function(series) {
    var bookNumber = 1;
    angular.forEach(series.book, function(book) {
        $scope.serieslist.push(
            {
                seriesNumber: seriesNumber,
                bookNumber: bookNumber++,
                seriesid: series.seriesid,
                name: series.name,
                book: book
            });
    });
    seriesNumber++;
});

For a live example, check out this plunker

Answer №3

Here is a functional JS fiddle

To implement nested ng-repeat, simply replace the DOM element as shown below:

<div ng-app='Your app'>
     <div ng-controller='Your controlelr'>
        <ul ng-repeat="series in serieslist">            
            {{series.name}} 
            <li ng-repeat="book in series.book" >{{ book.name }}</li>
        </ul>
      </div>
 </div>

You can also use the following code snippet for similar functionality:

<div ng-app='myApp'>
     <div ng-controller='Home'>
        <ul ng-repeat="series in serieslist">            
            <li ng-repeat="book in series.book" >{{ book.name }} of {{series.name}}</li>
        </ul>
      </div>
 </div>

Click here to view the final result on JS Fiddle

Answer №4

One way to simplify your list is by utilizing a tool like underscorejs to create a flat version, which you can then iterate over using ng-repeat. To learn more about how to accomplish this task, check out Karl's response to a similar query on stackoverflow at this link: How to flatten with ng-repeat

Answer №5

Data Transformation

$scope.serieslist = data.records;
    $scope.flatbooklist = [];
    angular.forEach($scope.serieslist, function (series)
    {
        angular.forEach(series.book, function (book)
        {
            $scope.flatbooklist.push({seriesname: series.name, seriesid: series.seriesid, bookname: book.name, bookid: book.bookid, bookimage: book.image});
        });
    });

Displaying Books

<ul ng-repeat="book in flatbooklist">
    <li>
        <div>{{book.seriesname}}</div>
        <div>{{book.bookname}}</div>
    </li>
</ul>

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

Angular Material failing to adapt to mobile devices

My website was created using Angular Material and looks great on desktop, but is completely broken and out of place when viewed on mobile devices. I'm thinking it might be because I haven't set the column size for each element properly. Any advic ...

Steps for transforming an array of objects into an array of values based on a specific key

Is there a way to extract messages based on keywords from a JSON structure? Here is an example of the JSON structure: [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}] I ...

Exploring CouchDB through Ajax to interact with a static website

Is it feasible for my HTML static website to interact with CouchDB using AJAX and retrieve the data without relying on server-side languages like PHP or Python? The CouchDB might be hosted on a different server/domain, so JSONP would need to be utilized. ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Following recursive loop JSON

I'm facing an issue with signalr where a self-referencing loop occurs when sending a response to the client. How can I resolve this problem in MVC5? In a typical ASP.NET MVC 5 project, I utilized the following code: config.Formatters.JsonFormatter.S ...

What steps do I need to take to deploy my React app onto a server?

I recently completed creating my first website with React and now I want to upload it to my server (HostGator). Can anyone guide me on how to do that? Thank you. ...

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

Python pymysql encountering a syntax error when trying to insert a JSON object

Encountered the following error when trying to insert data into a SQL database table using Python: pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the ...

The element "Footer" cannot be found in the file path "./components/footer/Footer"

After attempting to run the npm start command, I encountered the following error. In my code, I am trying to import the file /components/footer/Footer.js into the file /src/index.js //ERROR: Failed to compile. In Register.js located in ./src/components/r ...

DOM doesn't reflect changes to nested object when component prop is updated

I have a complex object structured in a multidimensional way that appears as follows: obj: { 1: { 'a' => [ [] ], 'b' => [ [] ] }, 2: { 'x' => [ [], [] ] } } This object is located in the r ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

Creating a Rails model without an associated HTML view involves generating the model using Rails scaffolding

Is there a way to ensure that my model always returns JSON, regardless of conneg or file-like extensions in the URI such as /app/model.json? I have tried searching online without much success, but I'm sure there must be a simple solution. ...

Using assert.rejects() in Mocha and Node: A Complete Guide

Following the instructions in the documentation, I attempted to use assert.rejects to test for an error message (I have Node version above v10). However, no matter what message I specify, the test always passes. What could be causing this issue? it("is f ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

Acquire a portion of a string with JavaScript or jQuery

Given the string testserver\sho007, how can I utilize jQuery to extract only the value sho007? ...

Error: The react render method is unable to determine the length of an undefined property

I created this component to extract the length of the followers array in order to display the number of followers each user has on their profile. The fetchUser() function is used to call a backend API, and I implemented Redux and Reselect for state managem ...

Aggregate the properties of objects in an array into a single object using Lodash

I've been struggling to figure this out on my own, so I decided to seek advice from those with more experience. I have an array of objects called items, and I need to sum up specific properties across different objects in the array. The user can selec ...

The functionality of Angular binding appears to be experiencing issues when used in conjunction with ngIn

On my timeline, I have posts displayed using a $firebaseArray that updates properly when there are changes. However, I noticed that when I try to bind other data, it only works when ngInfiniteScroll is fetching more data from Firebase, triggered by scrolli ...

Generating multiple circles on Google Map using ng-maps

I have reviewed several similar posts on SO, but I am still struggling to figure out my mistake. My goal is to place multiple circles on a Google map using a JSON string setup like this: [ {"name":"0","lat":30.45,"long":91.15}, {"name":"1","lat": ...

What is the best way to format a User object into JSON before sending it to an API endpoint?

Encountering an error 400 when attempting to submit a POST request. "$.User": [ "The JSON value could not be converted to WebApi.Models.User. Path: $.User | LineNumber: 5 | BytePositionInLine: 19." ] } Detailing my Order Model with ...