Whisher
Whisher

Reputation: 32806

Firebase angularfire how to update an item

I don't find the way to update an item (You can find all the code here) I tried with this code

app.factory('Items', function($firebase,FIREBASE_URL) {
    var ref = new Firebase(FIREBASE_URL);
    var items = $firebase(ref.child('items')).$asArray();
    var Item = {
        all: function () {
          return items;
        },
        create: function (item) {
          return items.$add(item);
        },
        get: function (itemId) {
          return $firebase(ref.child('items').child(itemId)).$asObject();
        },
        update: function (itemId, item) {
          return $firebase(ref.child('items').child(itemId)).update(item);
        },
        delete: function (item) {
          return items.$remove(item);
        }
    };
    return Item;
});

but it doesn't work. Can you help me, please ?

I've tried after the comment of Frank van Puffelen to

update: function (item) {
    return items.$save(item);
}

but it doesn't work and get me

Object { status=2, value="Invalid record; could d...ts key: [object Object]"}

You can see a workish example at :

https://lalista.firebaseapp.com

Upvotes: 1

Views: 4954

Answers (2)

Alex Ross
Alex Ross

Reputation: 3839

For anybody coming to this question using the new AngularFire APIs $firebaseArray and $firebaseObject, the methods are:

$firebaseArray.$save(recordOrIndex)

var list = $firebaseArray(ref);
    list[2].foo = "bar";
list.$save(2).then(function(ref) {
  ref.key() === list[2].$id; // true
});

$firebaseObject.$save()

var obj = $firebaseObject(ref);
obj.foo = "bar";
obj.$save().then(function(ref) {
  ref.key() === obj.$id; // true
}, function(error) {
  console.log("Error:", error);
});

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 600071

If you have an explicit update function, you're not using Angular's/AngularFire's two-way/three-way data binding. In that case you might as well bypass AngularFire for the update and call Firebase's JavaScript API directly:

 update: function (itemId, item) {
     return ref.child('items').child(itemId).set(item);
 }

Note that I call set instead of update, because it looks like you're trying to replace any existing data Firebase might be storing for the item.

Firebase's JavaScript API and AngularFire play nicely together here, so you don't have to worry about the data getting out of sync.

Upvotes: 4

Related Questions