gpt4 book ai didi

javascript - 如何将 firebase angularfire 数组排序为数周和数天?

转载 作者:行者123 更新时间:2023-11-29 10:14:19 24 4
gpt4 key购买 nike

我正在制作一个待办事项列表,该列表按周(基于添加日期和完成日期)对任务进行分组,并按一周中的几天对任务进行分组。数据库结构如下所示:

users
userA
tasks
taskobject1
taskobject2
..
userB
tasks
taskobject1
task object2

我正在使用 ng-repeat 将所有任务显示到每个用户的 View 中。我希望能够先按它们属于哪一周对它们进行排序,然后像这样:

#week1
--monday--
task a
task b
--tuesday--
task c
task d
..
#week2
--monday--
task a
..

即使是概念性的答案也会有所帮助。我不知道从哪里开始。

谢谢。

最佳答案

另请参阅这篇文章,其中提供了执行此分组的指令:Is it possible to .sort(compare) and .reverse an array in angularfire?

这里有几种方法可以采用。

按日期结构化的数据

如果记录总是被这个结构获取,你可以这样存储它们;

/users/usera/tasks/week1/monday/taska/...

然后您可以简单地在 tasks 级别将它们作为对象获取,您将获得一个预排序的 JSON 对象,其值嵌套在适当的级别。

这种方法与 AngularFire 的兼容性不高,AngularFire 旨在绑定(bind)对象或集合,而不是嵌套的数据树,但应谨慎使用。

使用优先级

第二种方法是 add priorities在任务上,这将是一个纪元时间戳。现在当你想获取它们时,你可以在树中的特定点开始/结束,并获取记录。每个都有一个时间戳,您可以使用它来识别周和日。

var ref = new Firebase(ref).startAt(twoWeeksAgo).endAt(nextThursday);
$scope.list = $fireabse(ref).$asArray();

但是,这不会对条目进行分段。您需要检查 ng-repeat 中的每个条目并动态添加 header :

// in the controller
var last = null;
$scope.priorityChanged(priority) {
/**
* here we would use a library like moment.js to parse the priority as a date
* and then do a comparison to see if two elements are for the same day, such as
**/
var current = moment(priority).startOf('day');
var changed = last === null || !last.isSame(current);
last = current;
return changed;
};

$scope.getDayName = function($priority) {
return moment($priority).format('dddd');
};

<!-- in the view -->
<li ng-repeat="item in list" ng-init="changed = priorityChanged(item.$priority)">
<h3 ng-show="changed">{{getDayName(item.$priority)}}</h3>
{{item|json}}
</li>

这种方法很容易与 AngularFire 兼容。

滚动你自己的列表

最后一种方法是去掉 AngularFire 并推出你自己的。例如,如果我们为每个任务存储星期和工作日,我们可以执行以下操作:

app.service('DatedList', function($timeout) {
return function(pathToList) {
var list = {};

pathToList.on('child_added', function(snap) {
$timeout(function() { // force Angular to run $digest when changes occur
var data = snap.val();
var week_number = data.week;
var week_day = data.day;
list[week_number][week_day] = data;
});
});

//todo: write similar processing for child_changed and child_removed

return list;
}
});

app.controller('ctrl', function($scope, DatedList) {
var listRef = new Firebase(URL).limit(500);
$scope.weeks = DatedList(listRef);
});

<div controller="ctrl">
<div ng-repeat="(week, days) in weeks">
<h1>{{week}}</h1>
<div ng-repeat="(day, items) in days">
<h2>{{day}}</h2>
<div ng-repeat="item in items">
{{item|json}}
</div>
</div>
</div>
</div>

关于javascript - 如何将 firebase angularfire 数组排序为数周和数天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25899951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com