如何在Ember.js中对模型进行排序?

时间:2013-07-29 11:54:58

标签: ember.js

我在Ember.js中使用这样的模型:

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

它从MyData接收数据。在我的数据中,我有一个名为“NAME”的字段。我想通过NAME以升序显示来自MyData的数据。

我添加了一个控制器(thx.Toran,直观),如下所示:

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

但我的模板是这样的:

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

仍显示无序列表。怎么做对了?

4 个答案:

答案 0 :(得分:18)

自问这个问题以来,

ArrayController已从Ember(v2.0)中删除。以下是在不使用ArrayController的情况下实现相同目标的方法:

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

然后:

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

here is the documentation对于Ember的计算sort宏。

答案 1 :(得分:15)

由于ArrayController包含SortableMixin(已在@ianpetzer的评论中提及),因此您可以在sortProperties中设置要排序的属性。

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

答案 2 :(得分:6)

确保您使用的是{{#each controller}},而不是{{#each model}},因为Controller将拥有自己的模型集合副本,并将其排序并呈现给模板。

<!-- ************************************************************************ -->
<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>

答案 3 :(得分:1)

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

确保您的find方法具有类似的功能

App.Person.reopenClass({
    people: [],
    find: function() {
        var self = this;
        $.getJSON('/api/people', function(response) {
            response.forEach(function(hash) {
                var person = App.Person.create(hash);
                Ember.run(self.people, self.people.pushObject, person);
            });
        }, this);
        return this.people;
    }
});

不是这个(这不会通过绑定更新模板,因为它是一个vanilla JS对象而不是一个完整的ember对象)

App.Person.reopenClass({
    people: [],
    find: function() {
        var self = this;
        $.getJSON('/api/people', function(response) {
            response.forEach(function(hash) {
                Ember.run(self.people, self.people.pushObject, hash);
            });
        }, this);
        return this.people;
    }
});