0

I am having this DS.Model

   Model = DS.Model.extend

  date: DS.attr "string"
  amount_payed: DS.attr "string"
  user_name:DS.attr "string"

`export default Model`

Currently there is nothing in my controller

Controller = Em.Controller.extend()

export default Controller

This is the route

 Route = Ember.Route.extend 

  model: () ->
    return @store.find "user-account"

`export default Route`

From server I m getting response in json with date value like

"date": "1995-12-25 00:00:00"

This is the sample template

{{#each detail in model}}
 <li>{{detail.date}}{{detail.amount_paid}}{{detail.user_name}}</li>
{{/each}}

How to I sort/filter the model in my controller so that when the template renders the model using {{#each detail in model}} the details with latest dates are displayed first.Basically I want to sort the model using date property.Remember date comes like "date": "1995-12-25 00:00:00". Will be ok if u guys can give a solution in javascript also(not necessarily coffescript)

4

1 回答 1

2

有几种方法可以做到这一点:computed.sort, SortableMixin, 实现自定义排序功能。

当前棘手的事情是您的日期是字符串,因此您需要将它们转换为可以运行比较的东西(数字时间戳或日期对象等)。您可以在排序期间(在排序函数中)或在模型本身上进行转换,以便您可以在应用程序的其他位置更轻松地重用和格式化日期。

我在下面提供的示例在排序期间进行转换。请注意,您不能只执行 (new Date(string)) ,因为 Safari 中的日期解析存在错误。

此答案假定使用 ember-cli 和从 Ember 2.0 开始是当前最佳实践的语法

文档computed.sort在这里:http ://emberjs.com/api/classes/Ember.computed.html#method_sort

import Ember from 'ember';

const {
  computed,
  Controller
} = Ember;

export default Controller.extend({
  sortedModel: computed.sort('model', function(a, b) {
    let timestampA = makeTimestamp(a);
    let timestampB = makeTimestamp(b);

    if (timestampA > timestampB) {
      return 1;
    } else if (timestampA < timestampB) {
      return -1;
    }
    return 0;
  })
});


// ideally you'd just return date, and call this makeDate
// and probably you'd do this when setting the date onto the model
function makeTimestamp(dateString) {
  let arr = dateString.split(/[- :]/);
  let date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
  date.setTime( date.getTime() - date.getTimezoneOffset() * 60 * 1000 );
  return date.getTime();
}

然后,您将像这样在模板中使用它。

{{#each sortedModel as |detail|}}
  <li>{{detail.date}}{{detail.amount_paid}}{{detail.user_name}}</li>
{{/each}}

快速说明,{{#each detail in model}}是一种不推荐使用的语法,从 ~1.10 开始的当前语法是{{#each model as |detail|}}.

于 2015-08-23T14:44:56.147 回答