How do I utilize ng-repeat in Angular to pass a variable that specifies the number of repetitions?

When working on my app, I encountered a situation where I needed to retrieve elements from a database and display them using ng-reat. Everything was going smoothly until I realized that within this list, there was another set of data that required a separate call to the database.

I wanted to pass an id to repeat an element based on the number of results returned and display their corresponding data. Here is an example of what I had in mind:

<div ng-repeat="library in libraries">
    <p>Read our books:</p>
    <p ng-repeat="book in books">{{book.title}}</p>
</div>

My initial thought was to do something like this:

<p ng-repeat="book in getBooks({library.id}) track by $index">{{book.title}}</p>

To achieve this, I planned to use the following function to handle the repeats and values:

$scope.getBooks = function(id){
    ...execute database query with the provided id...
    ...update scope to include the retrieved books...
    ....**magic**...
}

However, I was uncertain about whether this approach would be effective and how to properly update the scope to include the book titles. While I have used similar techniques to repeat a certain number of times before, handling an updated $scope was a new challenge for me.

Answer №1

To improve performance, I suggest pre-loading the data by using an Angular factory object like Corbin mentioned.

 angular.module('appName')
        .factory('DataManager', DataManager);

    function DataManager($log, $timeout, DataService) {
        var mngr, config = getConfig();  // any default values

        $log.debug('DataManager Init');

        mngr = {
            CurrentSearchTerm: null,
            Libraries: [],
            Abort: abort,
            GetData: getData  // Function call to get data.
        };

        // This call is your main ajax call, it could be one call to get the
        // full dataset of lib + books in json format.  Or multiple calls.
        function getData(){
            DataService.getData().then(function(response){
             //  ...parse data, etc...loop and :
             mngr.Libraries.push(parsedDataItem);
            };
        }


        return mngr;
   }

Once injected into your controller, you can then iterate over the data.

<ul>
  <li ng-repeat="library in mngr.Libraries">
     <!-- now you should have library.Books which was already sent down in the factory payload. -->
  </li>
</ul>

To simplify things further, consider using a directive for each repeat:

<library data="library">

This approach allows you to have a clean template and scope for each library.

angular('appName').directive('library',function(){
            return{
            restrict:'E',
            replace:true,
            templateUrl:'library.view.html',
            scope:{
                data:'='
            },
            controller:function($scope,$log){
                // Here $scope.data === library from your ngRepeat!
            }
        };
});

Lastly, if you want to load books on demand, you can add a method in the directive to 'getBooks' for a specific library object.

Hopefully, this explanation clarifies things for you.

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

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...

"Learn how to seamlessly submit a form and display the results without the need to refresh the

Here is the form and result div: <form action="result.php"> <input type="checkbox" name="number[]" value="11" /> <input type="checkbox" name="number[]" value="12" /> <input type="checkbox" name="number[]" value="13" /> <input t ...

Using VueJS to fetch and display data from a JSON file using

Currently, I am dealing with a JSON value in the following format: { "T1" : "online", "T2" : "offline" } Additionally, I have an online API which only sends me the following response: { StatusCode :"T1" } My task is to extract the code from the API res ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

Retrieving an array from the $.get() method within multiple nested loops

I'm currently working on a jQuery plugin that takes an array of JSON files and needs to compile them into one large array. While each part of the code works individually, I'm facing issues when trying to integrate them together and return the ne ...

What is the best way to showcase the chosen items in a dropdown menu?

There seems to be an issue with the selected item not appearing in the input field. export default function BasicSelect() { const [sortBy, setSortBy] = useState(""); const [condition, setCondition] = useState(""); const [delivery, ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

Steps to extract viewmodel information from a specific controller following an ajax request

I am encountering an issue with passing updated data from my controller to the view after making an Ajax call. Here is a simplified version of what I am trying to achieve: Javascript $ANALYZE = $('#submitID'); $ANALYZE.click(function () { ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

Avoiding the page from refreshing upon reload

Is it possible to prevent certain states from loading when the application is opened from a window reload or using the F5 key in AngularJs 1.6 with UI-Router and Html5 mode enabled? In my UI-Router configuration, I have: .state("recordform", { ...

Switching the phone formatting from JavaScript to TypeScript

Below is the JavaScript code that I am attempting to convert to TypeScript: /** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value) => { const areaCode = value.substr(0 ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...

Challenge implementing custom javascript to display categorical/string features on Shiny slider

I'm attempting to design a unique Shiny slider that represents the months of the year. My desired outcome is for the slider to display the names of the months as strings, rather than numeric values where 1 corresponds to January, 2 corresponds to Febr ...

What is the process of exporting a module assigned to a variable in JavaScript?

My approach to making the require visible in <app></app> is as follows: index.html: <script> var electron = require('electron') </script> <app></app> <script src="bundle.js"></script> App.vue: ...

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

What could be the reason for receiving the error message "Function call failed: String is not a function"?

I'm facing an issue while trying to respond to messages in my inbox. I initially assumed it would be a straightforward process similar to sending a regular message. Instead of using $scope.messageTo and $scope.messageFrom, I mistakenly entered my emai ...

"Dynamically generated websites, backend processing, React framework Nextjs, Content Management System WordPress

I'm interested in creating a primarily static site using Next.js, but I also need the ability to provide customers with price estimates based on their specifications. The calculation process needs to be kept private and not exposed to anyone else (oth ...

The issue of WithRouter Replace Component not functioning in React-Router-V6 has been encountered

As I upgrade react router to react router v6, I have encountered a problem with the withRouter method which is no longer supported. To address this issue, I have created a wrapper as a substitute. export const withRouter = Component => { const Wrappe ...

Tips for maintaining the selected radio button state after refreshing the JSP page: Ensuring that the radio button remains selected

I need help with refreshing a page after clicking on one of two radio buttons. I've tried multiple solutions but haven't been successful so far. Can someone assist me? <script> $(document).ready(function() { $(document).on('c ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...