Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort model in Ember.js?

Tags:

ember.js

I use a model in Ember.js like this:

App.SomethingRoute = Ember.Route.extend({
  model: function()
  {
      return App.MyData.find();
  }
});

It receives data from MyData. In my data i have a field called "NAME". I would like to display data from MyData in ascendant order by NAME.

I've added a controller (thx. Toran, intuitive) like this:

App.SomethingController = Ember.ArrayController.extend({
  sortProperties: ['NAME'],
  sortAscending: true
});

But my template that is like this:

{{#each model}}
 {{NAME}}
{{/each}}

Still shows unordered list. How to make it right?

like image 432
Tom Smykowski Avatar asked Jul 29 '13 11:07

Tom Smykowski


3 Answers

ArrayController has been removed from Ember (v2.0) since this question was asked. Here is how you would achieve the same without using an ArrayController:

export default Ember.Controller.extend({
  sortProperties: ['name:asc'],
  sortedModel: Ember.computed.sort('model', 'sortProperties')
});

And then:

{{#each sortedModel as |thing|}}
 {{thing.name}}
{{/each}}

And here is the documentation for Ember's computed sort macro.

like image 188
stephen.hanson Avatar answered Nov 13 '22 18:11

stephen.hanson


Since the ArrayController includes the SortableMixin (already mentioned in the comment from @ianpetzer), you can set the properties you want to sort on in sortProperties.

App.SomethingController = Ember.ArrayController.extend({
  sortProperties: ['name'],
  sortAscending: true
});
like image 15
intuitivepixel Avatar answered Nov 13 '22 17:11

intuitivepixel


Make sure you are using {{#each controller}}, not {{#each model}}, since the Controller will have it own copy of the model collection that it sorts and presents to the template.

<!-- ************************************************************************ -->
<script type="text/x-handlebars" data-template-name="tickets">  
<p>
<table id="tickets" class="table table-striped">
<thead>
  <tr>    
    <th {{action "sortByAttribute" "status"}}>Status</th>
  </tr>
</thead>
<tbody>
{{#each controller}}
    <tr>     
      <td>{{#link-to 'ticket' this.id}} {{status}} {{/link-to}} </td>
    </tr>
{{/each}}
</tbody>
</table>  
</p>
</script>
like image 6
tim Avatar answered Nov 13 '22 16:11

tim