big_water
big_water

Reputation: 3204

AngularFire how to remove multiple items from array?

I am using Firebase and the AngularFire library. I am looking for a way to remove all items or a range of items from a $firebaseArray object. I don't see a straightforward way to do it in the documentation. Is there some way I'm not thinking of other than looping and removing items one by one? Please tell me that's not the only way!!

Upvotes: 1

Views: 674

Answers (2)

Andreas
Andreas

Reputation: 1

I couldn't get the firebaseArray.$ref().remove() to work as the remove() function didn't exist on the object when ordered by child, but doing the following seemed to work though:

$firebaseUtils.doRemove(firebaseArray.$ref());

Upvotes: 0

cartant
cartant

Reputation: 58410

If there isn't a method in the $firebaseArray that does what you want, you can use the array's $ref() to perform Firebase SDK-style calls. The array content will be synchronized with the changes you make through the ref.

To delete all elements, call remove on the ref itself:

function removeAll(firebaseArray) {
  return firebaseArray.$ref().remove();
}

To remove a range, perform an update in which the keys to be removed are set to null:

function removeRange(firebaseArray, start, end) {
  var keys = {};
  if (end === undefined) {
    end = firebaseArray.length;
  }
  for (var i = start; i < end; ++i) {
    keys[firebaseArray.$keyAt(i)] = null;
  }
  return firebaseArray.$ref().update(keys);
}

Both functions return promises.

Upvotes: 1

Related Questions