How to loop through sorted array controller in ember.js?

by darrion.kuhn , in category: Javascript , 3 months ago

How to loop through sorted array controller in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 3 months ago

@darrion.kuhn 

You can loop through a sorted array controller in Ember.js by using the arrangedContent property of the array controller. The arrangedContent property stores the sorted version of the array that is being controlled by the array controller. Here is an example of how you can loop through a sorted array controller in Ember.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// In your controller or component
import Controller from '@ember/controller';

export default Controller.extend({
  sortedItems: Ember.computed.sort('model.items', 'sortDefinition'),
  
  sortDefinition: ['someProperty:asc'],

  // Loop through sorted items
  actions: {
    loopThroughItems() {
      this.get('sortedItems').forEach(item => {
        console.log(item.get('someProperty'));
      });
    }
  }
});


In this example, we have a controller that defines a sorted array controller using Ember.computed.sort with a sortDefinition property that specifies how the items should be sorted. The sortedItems property stores the sorted version of the model.items array. The loopThroughItems action logs the value of the someProperty property of each item in the sorted array controller.


You can then use the {{#each}} helper in your template to loop through the sorted items:

1
2
3
{{#each sortedItems as |item|}}
  {{item.someProperty}}
{{/each}}


This will loop through the sorted items and display the value of the someProperty property for each item.