ropz
ropz

Reputation: 128

How to apply a partial update to an object using AngularFire

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:

enter image description here

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

enter image description here

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();
          });
    }

Upvotes: 3

Views: 2704

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599591

As you found out yourself already:

  1. a FirebaseObject (as returned by $asObject()) does not have a $update method.
  2. when you call $save() on a FirebaseObject before it is completely loaded, you may end up deleting other properties

To patch existing data you can:

  1. Either wait for the entire object to be loaded (as you did in your update to the question)
  2. 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...

Upvotes: 4

Related Questions