AngularJS按时差排序

时间:2014-04-25 16:32:35

标签: javascript angularjs

我想启用每个表字段的排序。我有一列显示了在项目上花了多少分钟,但按此字段排序并不能正常工作。

<table>

   <th ><a href="" ng-click="sortBy='task.company_name'">Company</a></th>
   <th><a href="" ng-click="sortBy='timediff(task.time_start,task.time_stop)'">Time difference</a><th />

   <tr ng-repeat="task in tasks | orderBy:sortBy">
        <td >{[{ task.company_name }]}</td>
        <td >{[{ timediff(task.time_start,task.time_stop) }]}</td>
    </tr>

</table>

timediff功能:

$scope.timediff = function(start, end){
    var start = moment(start);
    var end = moment(end);
    var diff = end.diff(start,'minutes',true);
    return (diff/60).toPrecision(3);
};

Plunker http://plnkr.co/edit/vdkfNkgpdLUp9RgZ1IvO?p=preview

2 个答案:

答案 0 :(得分:2)

简单修复,只需将函数分配给参数

即可
<tr>
    <th><a href="" ng-click="sortBy='company_name'">Company</a></th>
    <th><a href="" ng-click="sortBy='timediff'">Time difference</a></th>
</tr>
<tr ng-repeat="task in tasks | orderBy:sortBy">
    <td>{{ task.company_name }}</td>
    <td>{{ task.timediff = timediff(task.time_start,task.time_stop) }}</td>
</tr>

Here is an updated plunker 显示此内容以及添加反向排序。

答案 1 :(得分:0)

自定义函数有一种更简单的工作方式。我稍微编辑了数据集,以便在&#34; Company&#34;之间切换。和&#34;时差&#34;更清楚一点。

选项1 DEMO):

如果属性名称没有更改,您可以执行以下操作:

$scope.timediff = function(task){
    var start = moment(task.time_start);
    var end = moment(task.time_stop);  
    var diff = end.diff(start,'minutes',true);

    return (diff/60).toPrecision(3);
};

在你的html中,将函数分配给你的sortBy变量:

<th ><a href="" ng-click="sortBy='company_name'">Company</a></th>
<th><a href="" ng-click="sortBy=timediff">Time difference</a></th>

<tr ng-repeat="task in tasks | orderBy:sortBy">
    <td >{{ task.company_name }}</td>
    <td >{{ timediff(task)}}</td>
</tr>

Angular会自动将当前项目传递到orderBy中定义的函数。

选项2(更灵活)DEMO):

如果要动态定义属性名称,可以返回另一个函数:

$scope.timediff = function(name1, name2){
    return function(item) {
        var start = moment(item[name1]);
        var end = moment(item[name2]);
        var diff = end.diff(start,'minutes',true);

        return (diff/60).toPrecision(3);
    }
};

并给它两个属性名称:

<th ><a href="" ng-click="sortBy='company_name'">Company</a></th>
<th><a href="" ng-click="sortBy=timediff('time_start', 'time_stop')">Time difference</a></th>

<tr ng-repeat="task in tasks | orderBy:sortBy">
    <td >{{ task.company_name }}</td>
    <td >{{ timediff('time_start', 'time_stop')(task)}}</td>
</tr>