Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop?

This is what I currently have:

obj:{
     a:3,
     c:5,
     d:1,
     g:15
}

Basically, I want to achieve something like this:

<div ng-repeat="item in obj | orderBy:'value'"> {{ item.value }}</div>

I am looking for a way to arrange that data presentation by either key or value. I understand that angular OrderBy only works with arrays and does not sort objects. However, if I could convert that object into an array of objects with key and value properties (possibly using a filter named 'toArray'):

var arr = [
  { 
     key:'a',
     value:'3'
  },
  {
    key:'c',
    value:5
  },
  ....
]

then I would be able to implement something like this:

<div ng-repeat="item in obj | toArray | orderBy:'value'"> {{ item.value }}</div>

However, every attempt at creating such a filter has resulted in a '10 $digest() iterations reached. Aborting!' error due to the constant updating of the new array of objects on each iteration.

What is the most effective (or any) solution for sorting a one-to-one object map without the need to modify the data structure in the controller?

Answer №1

If you're looking to add underscore functions to your angular.js code, consider using angular-underscore. With this, you can streamline your code by doing things like:

<div ng-repeat="item in values(obj) | orderBy:identity"> {{ item }}</div>

to extract only the values from your object; or

<div ng-repeat="item in pairs(obj) | orderBy:last"> Key: {{ item[0] }}; Value: {{item[1]}}</div>

to work with both keys and values simultaneously.

It's a simple integration that can really enhance your workflow. Check out a Plunker example here.

Answer №2

Consider starting off by initializing the array in your controller:

$scope.items = [];
for(var prop in data) {
    if(data.hasOwnProperty(prop)) {
        $scope.items.push({ key: prop, value: data[prop] });
    }
}

Then you can simply loop through items:

<div ng-repeat="item in items|orderBy:'value'">{{ item.value }}</div>

This way, you only fill the array once. It might be a concern if the object is fetched from an API call, but you could easily populate the array in the callback function.

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

Using v-model with the Toast-UI editor in Vue.js adds a dynamic and

Is there a way to bind the input value while using toast-ui vue-editor since it doesn't support v-model? Here is my setup for toast-ui: import '@toast-ui/editor/dist/toastui-editor.css'; import { Editor } from '@toast-ui/vue-editor&apos ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

"Error: Page not found - node.js and angular.js are unable

I've successfully set up the root route, but I'm encountering an issue with another route at 127.0.0.1:3000/dashboard. When I directly enter this URL into the address bar, I receive the following error: Cannot GET /dashboard However, if I creat ...

Calendars malfunctioning following the execution of npm run build

While utilizing the vue2-datepicker for a calendar, I encountered an issue during development. When clicking on the input box in my form, the calendar appeared as expected above the input. However, after running npm run build and loading up the resulting p ...

Having trouble getting NextJS to work with jsmpeg/node-rtsp-stream for displaying an RTSP stream

Exploring: https://github.com/kyriesent/node-rtsp-stream and How to display IP camera feed from an RTSP url onto reactjs app page? I attempted to showcase the RTSP stream from a CCTV but encountered an error. ReferenceError: document is not defined at scri ...

Stop unauthorized entry into JavaScript files

Is there a method to secure JavaScript files from unauthorized access? <script src="JS/MyScript.js" type="text/javascript"> It is crucial that users are unable to access the MyScript.js file. I am seeking advice on how to achieve this. Is it even ...

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

A step-by-step guide on how to render a view in AngularJS only after the model

Is there a way to delay loading my view in AngularJs until after my modal is fully prepared? I want to avoid using the $timeout function. Currently, when I launch the page, it appears blank at first and then gradually loads with the data. Any suggestions ...

The algorithm for editing multiple phone numbers

I'm working on a form for my project that requires saving 4 phone numbers. The text boxes for entering the phone numbers are revealed on button clicks. Here's what I need to implement: When adding entries---> Enter the first phone number. C ...

`Using angular-ui-tree: Retrieving the html element of the most recent node that was added`

Perhaps this question may seem trivial, but despite my efforts to research on stackoverflow and angular-ui-tree documentation, I have not been able to find a solution. I am in need of obtaining the HTML element of the most recently added node. To be spec ...

Having trouble resolving an error while attempting to incorporate an npm module into a vanilla JavaScript application

I admit my lack of expertise in building modern JavaScript apps is becoming evident. Currently, we have a Capacitor app that uses plain JavaScript without any build tools, and it functions well. Our goal is to incorporate Microsoft Code Push support throu ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

What is the way to create the appearance of a hand or arrow hovering over my "X" while I am closing out my Div using jQuery?

Hey there, I've got a handle on closing the div using a "p" tag in jQuery. The code snippet for that is provided below. However, I'm looking to change the cursor over the "X" to an arrow or hand symbol, similar to what you'd see with an "a" ...

Validation for required fields in AngularJS forms may not always be triggered upon loading

When loading a form with a required text field that initially has an empty value, the controller validates the field and marks it as an error. I would like to prevent this initial validation and only validate the field after an onblur event. <input dat ...

Employing require.js, one can integrate a distinctive form of non-concatenated dat.gui source. This allows for the seamless

Excuse the SEO-friendly title, but I want to ensure that everyone can access the issue I'm currently working on. For those interested in customizing the appearance of dat.gui, you will need to download the source and include it using require.js follow ...

Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below: export interface IMyObjectFromAPI { status: { ...

Tips for uploading information to a web service

Issue Description:- I am attempting to access web services from a different domain (i.e. Systems are not locally connected) and encountering the following error: "Failed to load : Response for preflight is invalid (redirect)" var username = "<a href= ...

"Maintaining the checked state of a radio button list in AngularJS and updating the

Show me with a plunker example http://plnkr.co/edit/m8cvxA?p=preview In the settings page I am working on, administrators can define default settings for each site. In the provided plunker, when you change your selection using the radio buttons and click ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Browser local storage protection

Utilizing local storage to preserve specific data for my website has been beneficial. Each necessary object is stored so that users can access them on their browser (in chrome: Resource -> Local Storage). My objective now is to make these objects unrea ...