问题
The $save()
in Angularfire 0.8 is confusing me.
Here's a minimal example - a snippet from my controllers.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 addNode()
is called, sure enough, a node is created in my firebase:

But when addAttribute()
is called, the entire record is replaced, rather than what I expected, which was for the 'lastname' attribute to be added.

I've no doubt misunderstood the docs. Can anyone help?
Update:
OK, I needed to wait until the object was loaded. It works now, after 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();
});
}
回答1:
As you found out yourself already:
- a
FirebaseObject
(as returned by$asObject()
) does not have a$update
method. - when you call
$save()
on aFirebaseObject
before it is completely loaded, you may end up deleting other properties
To patch existing data you can:
- Either wait for the entire object to be loaded (as you did in your update to the question)
- Or call
$firebase.$update
directly
$firebase(FB).$update({ lastname: "Bond" });
This last approach has the advantage that you don't pull down the entire object, only to update a single property. Note that this is probably premature optimization in most cases, but still...
来源:https://stackoverflow.com/questions/26035526/how-to-apply-a-partial-update-to-an-object-using-angularfire