如何使用AngularFire将对象移动到数组的顶部

How to move an object to the top of an array with AngularFire?

本文关键字:数组 顶部 移动 对象 何使用 AngularFire      更新时间:2023-09-26

我正在尝试使用AngularFire将对象移动到数组的顶部。

我在Firebase中的数组与此类似:

$scope.todos = [
    {title:"Work out", timetag:"new Date()", done: false },
    {title:"Home work", timetag:"new Date()", done: false }
];

我创建了一个使用香草javascript的函数,该函数将对象存储到变量中。该函数从数组中删除要移动到数组开头的对象。然后,该函数将存储到变量中的对象替换到数组的开头。

这是我的代码:

$scope.moveUpPriority = function($index){
    var toMove = $scope.todos[$index];
    delete $scope.todos[$index];
    $scope.todos.splice(0,0, toMove);
    $scope.todos.$save();
  };

这个代码片段几乎完全按照我想要的方式工作。当我在我的待办事项列表上运行它时,它会将待办事项任务向上移动数组。但是,当我刷新页面时,它不会粘住。

有哪些合适的 AngularFire 方法可以将这种类型的 JavaScript 代码完全保存或设置为我的 Firebase 后端?

要保留 TODO 的顺序,您可以添加一个名为 priority 的属性。

当 TODO 在优先级列表中向上拖动/移动时,您应该重新设置保存它们的 TODO 的优先级值,并按模板中的该属性对它们进行排序。

好的,像splice(),push(),pop(),shift(),unshift()和reverse()这样的数组方法会导致Firebase Array崩溃。

  • 所以我的解决方法是使用标准的Javascript Array方法编辑/更改数组。
  • 然后我将本地(编辑的)状态数组的副本存储到变量中。
  • 然后我删除了 Firebase 数组。
  • 然后我把本地数组的键推到了Firebase。

下面是代码:

$scope.moveUpPriority = function($index){
    var toMove = $scope.todos[$index]; //save copy of $index todo
   $scope.todos.splice($index,1); //removes item at $index 
   $scope.todos.splice(0,0, toMove); //adds item toMove to the start of array
   var backup = $scope.todos; //copy back up array

   for(var b = 0; b<= $scope.todos.length; b++){
    $scope.todos.$remove($scope.todos[b]); //remove items from array
   }
   for(var i = 0; i<= backup.length; i++){
    $scope.todos.$add(backup[i]); // add items from back up array
   }
 };