2013-07-29 25 views
9

我使用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}} 

仍顯示無序列表。如何使它正確?

+0

http://emberjs.com/api/classes/Ember.SortableMixin.html – ianpetzer

+0

你可以顯示你的find方法的實現嗎?你需要使用ember對象(不是普通的JS對象)來獲得綁定行爲,這將會重新對它進行排序。 –

回答

15

由於ArrayController包含SortableMixin(已在@ianpetzer的評論中提及),因此您可以設置要排序的屬性sortProperties

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

我已更新問題,因爲我無法使其工作。請幫忙。謝謝。! –

+0

@tomaszs,你的應用程序中必須有其他事情發生,但它不會起作用,你能用你的設置更新你的jsbin/jsfiddle嗎? – intuitivepixel

+7

你的答案幫助了我,我只需要將{{#each model}}更改爲{{#each controller}}。 thx –

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

確保您的查找方法做這樣的事情

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; 
    } 
}); 

不是這個(因爲它是一個香草JS對象,而不是一個完全成熟的餘燼對象,這將不會更新通過結合模板)

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; 
    } 
}); 
+0

我更新了問題,因爲我無法使它工作。請幫忙。謝謝。 –

6

確保您使用{{#each控制器}},而不是{{#each模型}},因爲控制器將有它自己,它排序並呈現在模板的模型集合的副本。

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

ArrayController已經從灰燼(V2.0),因爲這個問題被問刪除。這裏是你將如何實現同樣沒有使用ArrayController

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

然後:

{{#each sortedModel as |thing|}} 
{{thing.name}} 
{{/each}} 
爲Ember的計算 sort宏觀

而且here is the documentation

+1

如果我將更改排序順序,該怎麼辦?如何重新渲染模型? – Meliborn

相關問題