Loop through unique IDs using AngularJS ng-repeat

I am just starting to delve into AngukarJS and ionic framework, embarking on the journey of creating an app with a structured tree layout as follows:

Home Tab (list of books) (templates/allbooks.html)
> unique book (book description and chapters) (templates/book-des.html)
>> unique chapter (templates/book-chapter.html)

Here's the content found in books.js

.factory('Books', function() {

  // storing books data
  var books = [{
    id: 0,
    title: 'Sample Title',
    author: 'Sample Author',
    category: 'Horor, Fiction',
    cover: '/cover.jpeg',
    details: 'some details about the book',
    chapters: [
      {
        id : 1,
        name: 'Chapter 1',
        filename: 'chapter1.html',
      },
      {
        id : 2,
        name: 'Chapter 2',
        filename: 'Chapter2.html',
      }
    ]
  }
  .....


    return {
     ...
    // get book by ID
    get: function(bookId) {
      for (var i = 0; i < books.length; i++) {
        if (books[i].id === parseInt(bookId)) {
          return books[i];
        }
      }
      return null;
    },
    // get chapter by ID
    getChapter: function(chapterId){
      for(var j = 0; j < books.chapters.length; j++){
        return j;
      }
      return null;
    }
  };

And this is what you'll find in controllers.js

....
.controller('BookDesCtrl', function($scope, $stateParams, Books) {
  $scope.book = Books.get($stateParams.bookId);
})
.controller('BookChapterCtrl', function($scope, $stateParams, Books) {
  $scope.book = Books.get($stateParams.bookId);
  // issue arises when trying to fetch chapter ID
  $scope.chapter = Books.getChapter($stateParams.chapterId);
})
.....

In the templates/allbooks.html, I employed the following ng-repeat

<div ng-repeat="book in books">
  <p>{{book.title}}</p>
  <p>{{book.author}}</p>
  <p>{{book.category}}</p>
</div>

This effectively lists all the available books

In the templates/book-des.html, another ng-repeat is used to display the contents as per book:

<div class="book-title">
   <p>{{book.title}}</p>
</div>
....
<div ng-repeat="chapter in book.chapters">
      <ion-item href="#/tab/books/chapter/{{book.id}}/{{chapter.id}}">
        <p>{{chapter.name}}</p>
      </ion-item>
</div>

Now, it pulls the current book's title and enlists all its respective chapters. Smooth sailing so far.

However, in the templates/book-chapter.html, my objective is to spotlight the specific chapter's related contents.

I attempted using

ng-repeat="chapter in book.chapters.id"
but to no avail.

The primary question stands here:

Within the templates/book-chapter.html template:

<div ng-repeat="chapter in book.chapters.id">
      <ion-item class="item item-text-wrap">
      <p><div ng-include="'{{chapter.filename}}'"></div></p>
      </ion-item>
      <p> chapter ID is {{chapter.id}} </p>
</div>

How can I utilize the ng-repeate feature in that template to extract information pertaining to that specific chapter?

Answer №1

Enhanced Template

  <ion-item class="item item-text-wrap">
  <p><div ng-include="'{{chapter.filename}}'"></div></p>
  </ion-item>
  <p> chapter Identification: {{chapter.id}} </p>

Upgrade your controller - .

controller('BookChapterCtrl', function($scope, $stateParams, Books) {
 var book =  Books.get($stateParams.bookId);
  $scope.book = book;
  // Fixing error in fetching chapter ID
  $scope.chapter = Books.getChapter(book, $stateParams.chapterId);
})

Modify your app.js

getChapter: function(book, chapterId) {
  for (var i = 0; i < book.chapters.length; i++) {
    if (book.chapters[i].id === parseInt(chapterId)) {
      return book.chapters[i];
    }
  }
  return null;

}

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

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

How to simultaneously play a sound and display an alert message using JavaScript

My JavaScript code attempts to play a sound and then display an alert, but the alert always shows up first. When I click 'ok', the sound plays. How can I make it so that the sound plays before the alert appears? <script> function play() { ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

I'm having trouble getting the second controller to function properly in my AngularJS application

I've been looking everywhere for a solution on how to implement two controllers, but I can't seem to get it working. Could there be something wrong with my HTML or could the issue lie in my script? Here is the JavaScript code: <script> v ...

Trigger function when the element is generated

Is there a way to execute a function only once while still having it run each time a new element is created using v-for? <div v-for"value in values"> <div @ function(value, domElement) if value.bool===true @> </div> ...

When attempting to utilize res.sendfile, an error arises indicating that the specified path is incorrect

I am facing an issue with my Express.js server and frontend pages. I have three HTML and JS files, and I want to access my homepage at localhost:3000 and then navigate to /register to render the register.html page. However, I am having trouble specifying t ...

Is it possible to implement marker dragging in Google Maps v3 using JavaScript? How can this be achieved?

I am currently using this code to search for an address, drop a marker, and drag it afterwards. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title&g ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-outer-1 br2"> <!-- ...

Is there a way to prevent a web page from refreshing automatically for a defined duration using programming techniques?

I am currently working on a specific mobile wireframe web page that includes a timer for users to answer a question after the web content body has loaded. There are two possible outcomes when answering the question: 1) If the user fails to answer in time, ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...

Determine the Height of the Container once the Font File has Finished Loading

When styling a website with a unique font using @font-face, the browser must download the font file before it can display the text correctly, similar to how it downloads CSS and JavaScript files. This poses an issue in Chrome (v16.0.912.63) and Safari (v5 ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

Initializing ng-app with a specific name will prevent the initialization of variables

Here is the code snippet I am working with: <div ng-app="" ng-init="show_login=false;count=0"> <button> ng-click="show_login=!show_login;count=count+1">INSPIRE</button> <form ng-show="show_login"> Username <input type="t ...

Guide on programmatically changing the position of a shape in SVG

Check out this tutorial on how to make SVG elements draggable using JQuery and Jquery-svg. The accepted answer provides an implementation for moving a circle by changing the cx and cy attributes. But how can I achieve drag-and-drop functionality for a pol ...