Jason Burnett
Jason Burnett

Reputation: 9

How to sort Ember Data model output?

I've searched and searched, but all the examples seem either outdated, aren't in the file structure enforced by Ember CLI, etc.

Anyway, say I have a model in app/models/employee.js:

export default DS.Model.extend({ firstname: DS.attr('string'), lastname: DS.attr('string'), });

And a route in app/routes/employees.js:

export default Ember.Route.extend({ model: function() { return this.store.findAll('employee'); }, });

And a template in app/routes/employees.hbs:

{{#each model as |employee|}} <tr><td>{{employee.firstname}}</td><td>{{employee.lastname}}</td></tr> {{/each}}

What do I need to add to sort that table by firstname, for example?
I gather I'm supposed to use Ember.computed.sort(), something like:

sortedEmployee: Ember.computed.sort('employees', ['firstname'])

And then do {{#each sortedEmployee as ...}} in the template, but I'm apparently not defining sortedEmployee in the right place.

Upvotes: 1

Views: 1358

Answers (2)

Kit Sunde
Kit Sunde

Reputation: 37075

app/controllers/employees.js

export default Ember.Controller.extend({
  sortProperties: ['firstname:asc'],
  sortedEmployees: Ember.computed.sort('employees', 'sortProperties')
});

app/routes/employees.hbs:

{{#each sortedEmployees as |employee|}}
  {{employee.firstname}}
{{/each}}

Example in JSbin: http://emberjs.jsbin.com/regowa/7/edit?html,css,js,output

Upvotes: 3

Frank Treacy
Frank Treacy

Reputation: 3716

You are on the right track, try the following:

sortProperties: ['firstname:asc'],  // or just 'firstname', or 'firstname:desc'
sortedEmployee: Ember.computed.sort('employees', 'sortProperties')

I think it's weird to have to define an extra property on the component/controller, but that way it works.

Upvotes: 2

Related Questions