How to apply partial update to an object using AngularFire
$save()
in Angularfire 0.8 confuses me.
Here's a minimal example - snippet of my controller.js file:
.controller('LandingPageController', ['$scope','$firebase', function($scope,$firebase) {
$scope.addNode = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/');
var fbr = $firebase(FB);
fbr.$set(1,{firstname: 'James'});
}
$scope.addAttribute = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
var fbr = $firebase(FB).$asObject();
fbr.lastname = "Bond";
fbr.$save();
}
}])
When called addNode()
, of course, in my firebase a node is created:
But when called addAttribute()
, the entire entry is replaced, not the expected one that was added for the "lastname" attribute.
I have no doubt misunderstood the docs. Can anyone please help?
Update:
OK, I needed to wait until the object was loaded. Now it works by changing addAttribute
to:
$scope.addAttribute = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
var fbr = $firebase(FB).$asObject();
fbr.$loaded().then(function() {
fbr.lastname = "Bond";
fbr.$save();
});
}
source to share
As you already learned:
- a
FirebaseObject
(as returned$asObject()
) has no method$update
. - when you call
$save()
onFirebaseObject
before it is fully loaded you can remove other properties
To correct existing data, you can:
- Wait for the whole object to load (as in your update to the question)
- Direct call
$firebase.$update
$firebase(FB).$update({ lastname: "Bond" });
This latter approach has the advantage that you are not pulling out the entire object, but only to update one property. Note that in most cases this is probably a premature optimization , but still ...
source to share