简单的ember表头排序

时间:2015-03-03 02:02:22

标签: sorting ember.js html-table

我有一个ember应用程序,我有一个表。我正在尝试做一个简单的列标题排序,但似乎无法让它工作或找到任何体面的例子如何做到这一点。任何援助将不胜感激。

links.hbs:

<thead>
    <tr>
        <th {{action "sortBy" "linkID"}}>ID</th>
        <th {{action "sortBy" "name"}}>NAME</th>
        <th {{action "sortBy" "description"}}>DESCRIPTION</th>
        <th {{action "sortBy" "url"}}>URL</th>
        <th {{action "sortBy" "effDate"}}>EFFECTIVE DATE</th>
        <th {{action "sortBy" "endDate"}}>END DATE</th>
        <th {{action "sortBy" "secr"}}>SECURITY RESOURCE</th>          
    <tr>
</thead>

links.js(控制器):

import Ember from 'ember';

export default Ember.ArrayController.extend({
    actions:{
            sortBy: function(property) {
                alert('Hello');
                this.set('sortProperties', [property]);
                this.set('sortAscending', !this.get('sortAscending'));
            }
    }

});

2 个答案:

答案 0 :(得分:2)

假设您正在迭代model来构建表,最简单的方法(对代码进行少量更改)可以实现这一点,只需将model设置为{{3每次排序时(sortedProperties更改时):

<强>控制器:

export default Ember.ArrayController.extend({
    sortProperties: ['name'],
    sortAscending: false,

    actions:{

        sortBy: function(property) {
            this.set('sortProperties', [property]);
            this.toggleProperty('sortAscending');
            this.set('model', this.get('arrangedContent'));  // set the model to the sorted array
        } 
    }
});

<强>模板:

<table>
    <thead>
        <tr>
            <th {{action "sortBy" "linkID"}}>ID</th>
            <th {{action "sortBy" "name"}}>NAME</th>
            <th {{action "sortBy" "description"}}>DESCRIPTION</th>
            <th {{action "sortBy" "url"}}>URL</th>
            <th {{action "sortBy" "effDate"}}>EFFECTIVE DATE</th>
            <th {{action "sortBy" "endDate"}}>END DATE</th>
            <th {{action "sortBy" "secr"}}>SECURITY RESOURCE</th>
        </tr>
    </thead>
    <tbody>
    {{#each item in model}}
        <tr>
            <td>{{item.linkID}}</td>
            <td>{{item.name}}</td>
            <td>{{item.description}}</td>
            <td>{{item.url}}</td>
            <td>{{item.effDate}}</td>
            <td>{{item.endDate}}</td>
            <td>{{item.secr}}</td>
        </tr>
    {{/each}}
    </tbody>
</table>

<强> arrangedContent

<强> Here is a sample

如果您需要自定义比较器功能(例如比较日期时),您可以覆盖Here is a full demo挂钩,Ember会在比较元素进行排序时自动调用它。传递到sortFunction的参数是与sortProperties的内容对应的属性值。

例如,对于数组[ {name: "bob"}, {name: "john"} ]

// ...
sortProperties: ['name'],
sortFunction: function(propA, propB) {
    // propA === "bob"
    // propB === "john"
    if (propA < propB) {  
        return -1;
    }
    if (propA > propB) {  
        return 1;
    }
    return 0; // a must be equal to b
}
// ...

答案 1 :(得分:0)

我在这里为你准备了一个简单的例子:http://jsbin.com/yilucefuwi/1/edit?html,js,output

如果没有看到你的身体以及如何分配阵列控制器的内容,很难说出你做错了什么。 您确定#each块正在遍历项目控制器,而不是直接通过模型吗?