How to sort model in ember.js?

by mallory_cormier , in category: Javascript , 3 months ago

How to sort model in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 3 months ago

@mallory_cormier 

In Ember.js, you can sort a model by using the sortBy method in your template or in your controller.

  1. Sort model in template: To sort a model in your template, you can use the each helper and pass in a sorted version of the model using the sortBy method. For example, if you have a model called items and you want to sort it by a specific property, you can do the following:
1
2
3
{{#each (sortBy items "propertyName") as |item|}}
  <p>{{item}}</p>
{{/each}}


Replace "propertyName" with the property you want to sort the model by.

  1. Sort model in controller: To sort a model in your controller, you can use the sort method to sort the model before passing it to the template. For example, if you have a controller called items and you want to sort the model by a specific property, you can do the following:
1
2
3
4
5
6
7
import Controller from '@ember/controller';

export default Controller.extend({
  sortedItems: Ember.computed('model', function() {
    return this.get('model').sortBy('propertyName');
  }),
});


You can then use the sortedItems property in your template to display the sorted model:

1
2
3
{{#each sortedItems as |item|}}
  <p>{{item}}</p>
{{/each}}


Replace "propertyName" with the property you want to sort the model by.