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

Guide to placing a button on the same line as text with the use of JavaScript

Does anyone know how to add a button to the right of text that was added using JS DOM? I've tried multiple techniques but can't seem to get it right - the button always ends up on the next line. Any tips on how to achieve this? var text = docu ...

Avoid the problem of animations triggering twice when clicking

Hey there, I am facing an issue with my slider. If you could take a look at this website , you will notice that after clicking on the arrows, the slider behaves asynchronously. It changes speed rapidly at times and then slows down, repeating this pattern ...

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

Unable to process JSON array

One issue I'm facing is with an 'onload' handler for my web page. The javascript function 'handleLoad()' that it calls has suddenly stopped working, specifically not being invoked after attempting to pass the output of json_encode ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

Error message: "Issue occurs when sending keys to protractor element's text value and

Having trouble running this code in Protractor as I keep encountering errors, and I'm unable to retrieve the value of the anpr_box_input text. Error message: ManagedPromise::871 {[[PromiseStatus]]: "pending"} failed - should have a valid license ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application: <div class="work-item"> <div class="image-container"> </div> <div class="text-container"> </div> </div ...

Difficulty displaying API information on a web browser with react.js

I am currently working on developing a trivia game using React.js Typescript and The Trivia API. I have been successfully passing data between components with useContext and navigating through components using react-router-dom. However, I encountered an is ...

Challenges with optimization in AngularJS and Angular Material

Currently, I am working on an AngularJS application that utilizes 7 Angular Material tabs. One issue I have encountered is a significant amount of animation lag when switching tabs or opening a md-select element. According to Chrome Developer Tools, the fr ...

Angular - delete nested item

Incorporated the ng-nestable feature into our project and encountered an issue. I have included a button in this code section to remove items from the collection/json data. However, the ng-click function is not functional as expected. Clicking on one of ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

Media queries in CSS appear to be dysfunctional when used on Microsoft Edge

@media (min-width: 992px) and (max-width: 1140px) { .mr-1024-none { margin-right: 0px !important; } .mt-1024 { margin-top: 1rem !important; } .d-1024-none { display: none !important; } } Utilizing the ...

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Preventing Shift: How to Only Replace the Chosen Vue Draggable Item Without Affecting Other Grid Items

Let's try an example to demonstrate: https://codesandbox.io/s/j4vn761455?file=/src/App.vue:112-116 Step 1: Drag item 4 to where 5 is. Notice how 4 and 5 switch positions. Step 2: Now, drag item 1 to position 6. Watch as 1 moves to where 6 was, pushi ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Is Node.js functioning properly, but how can I incorporate it into a web browser?

I have a SQL Server table that I want to display in a web browser using the DataTables jQuery plugin. The code below works well for outputting data in the command line, but I need it to be displayed in the browser, possibly in JSON format. I am utilizing ...

Locate the generated ID of the inserted child when saving the parent in MongoDB

If I have a document representing a post with comments like the one below: { "_id": "579a2a71f7b5455c28a7abcb", "title": "post 1", "link": "www.link1.com", "__v": 0, "comments": [ { "author": "Andy", "body": "Wis ...

Filtering in AngularJS can be done based on the comma-separated elements

I am trying to implement a filter in AngularJS for a specific JSON format value [ {"id":"1","video_title":"Sample1","tags":"2,12,13","featured":"1"}, {"id":"2","video_title":"Sample2","tags":"5,13","featured":"1"}, {"id":"2","video_title":"Sample3","ta ...

What benefits are there to converting a jQuery application to Angular?

If I have a basic landing page with jQuery effects that I want to upgrade by "angularizing" it with AngularJS, how could I do so? For example, when using AngularJS for a contact form, it's known to be simple to implement. When considering DOM effects ...