Using the AngularJS limitTo filter in ngRepeat for an object acting as a dictionary

Can the limitTo filter be used on a ngRepeat directive that is iterating over the properties of an Object instead of items in an Array?

Although it is stated in the official documentation that the limitTo input should be an array or string, I am curious if there might be a way to make this work.

For reference, here is a snippet of the code:

<li ng-repeat="(key, item) in phones_dict |orderBy:'-age'| limitTo:limit_items"></li>

Where $scope.phones_dict represents an Object structured like this:

{ 
     item_1: {name:"John", age: 24},
     item_2: {name:"Jack", age: 23}
}

Answer №1

Utilizing limitTo is effective for strings and arrays, but when dealing with objects, it's best to create your custom filter like this:

myApp.filter('myLimitTo', [function(){
    return function(obj, limit){
        var keys = Object.keys(obj);
        if(keys.length < 1){
            return [];
        }

        var ret = new Object,
        count = 0;
        angular.forEach(keys, function(key, arrayIndex){
            if(count >= limit){
                return false;
            }
            ret[key] = obj[key];
            count++;
        });
        return ret;
    };
}]);

For a demonstration, check out the fiddle here: http://jsfiddle.net/wk0k34na/2/

Answer №2

After experimenting, I discovered a solution:

 ng-if="$index < limit"

By including the above code in the ng-repeat tag, I was able to achieve the desired outcome. While this method may not be considered conventional, it worked for me.

Answer №3

Another possible solution is to utilize 'track by $index'... This way, your limitTo function should look like this:

limitTo: $index == 5 (or any other number)

Answer №4

The updated limitTo filter now includes support for array-like objects (view example) starting from version 1.5.7.

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

The transformation rotation applied in CSS must not have any impact on the styling of my span and paragraph

Snippet: .details-section{ background-color: rgb(83, 83, 83); height: 200px; } .icon-container{ border: 2px solid #c49b63; width: 90px; height: 90px; transition: 0.5s ease; } .box i{ font-size: 60px; color: black; margin-top: 13px ...

How to resolve CORS issues in an AngularJS, Spring Boot, and Nginx setup

For the past few days, I've been struggling with an issue. I have a backend server set up using Spring-boot with Rest API. This server is being called from a frontend interface built with AngularJS and managed by Nginx. Everything is running locally ...

Vue.js powered search bar for exploring countries worldwide (utilizing the restcountries API)

Despite successfully loading the API country data (as evidenced by the console.log() entry and the accompanying picture of my work desk), the country information does not display when hovering the mouse cursor over the search bar field (expecting a dropdow ...

Ideas and Recommendations for Building a Laravel and Vue.js Hybrid Structure for MPA/SPA Applications

Consider the innovative approach I've been pondering - a combination of MPA and SPA, where each page functions as a Single Page Application, yet still reloads when navigating from one page to another (e.g. index.blade.php to posts.blade.php) like a tr ...

What is the purpose of using the variable "header_row || 1" in App Script?

Recently, I stumbled upon a spreadsheet that contains app script for gathering keys of data requested through doGet. In the code, there is a line that reads like this: var headRow = e.parameter.header_row || 1; What exactly does this line mean? I searc ...

Trouble Loading HTML Template Post Email Dispatch in Django

In my Django project, I have set up functionality to send an email after a form submission using the smtplib module. The email is sent successfully, but for some reason, I'm encountering an issue where the corresponding HTML template (delivery_email_s ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

merge various useState functions for appending values to an array into a unified function in a React component

I am currently facing a challenge with code complexity. I have 8 arrays where I need to add items based on a button click. As of now, I have created 8 separate functions for each task. Is there a way to consolidate all these functions into one function tha ...

Avoiding leaps through the use of dynamic pictures?

Currently, I am implementing the picture element along with srcset to download the same image but in varying resolutions depending on the screen size of the device. The image has a style of max-width: 100%, causing it to shift the content below when downl ...

Retrieving JSON data and showcasing it in HTML components

I'm attempting to retrieve JSON responses and showcase them within my predetermined HTML elements. I'm utilizing graphql from datocms. The API explorer displays the following for my model: query MyQuery { allNews { id newsTitle new ...

Angular: What is the best way to pass usersearch-input data to a different component and use it to generate a list of search results?

Seeking assistance as a beginner in Angular, I am currently working on my first project with Angular 8 for the frontend of an application. The challenge I faced was creating an HTML page (...stuff/searches) where users can input search criteria to find sp ...

Using Node.js, Handlebars, and Express for template inheritance

As I embark on my Node.js learning journey, I am starting with creating simple applications to grasp the fundamentals. Recently, I wanted to implement a Django-like template structure in my projects but found myself stuck on how to achieve it. I have come ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...

What is the best way to change an image using JavaScript?

Is there a way to change an image when the tag doesn't have an id? <img src="URL_1" /> I need to replace URL_1 with URL_2 Any suggestions on how to do this? ...

Is there a way to obtain the "rotated" coordinates of a mouse click within a canvas element?

Exploring New Features Within my image editing software, there is a canvas where users can draw shapes. These shapes are sent to a server and added to an XML file, which is then returned to the client for display. Now, I am looking to enhance the program ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

What is preventing the X-Powered-By Header from being disabled even after implementing helmet security measures?

After incorporating Helmet into my Express application and configuring it in app.js with the following code: app.use(helmet()); const helmet = require('helmet'); Upon restarting the app, the X-Powered-by header is still enabled despite using app ...

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

Obtaining an array of weeks for the previous two months from the current date using JavaScript

Looking to generate a list of weeks for the past two months using JavaScript. Any suggestions on how to accomplish this task would be greatly appreciated. [ { "week_start": "8/01/2016", "week_end": "8/06/2016" }, { "w ...