CraexIt
CraexIt

Reputation: 179

AngularFire: How to apply partial update (a single field) to an item in $firebaseArray?

I'm wondering how I can apply a partial update to an item in $firebaseArray, and the documentation is confusing with no mention of this. .$save seems to clobber the entire item:

var ref = new Firebase("https://xxxx.firebaseio.com/items");
$scope.items = $firebaseArray(ref);
someItem = getItem();
someItem.newField= 'Test';
$scope.items.$save(someItem);

This causes the entire item object to be completely overridden, instead of just updating newField

I've seen other discussions of how to do this using $asObject but I'm still confused how to handle this with items in a $firebaseArray

Upvotes: 3

Views: 2686

Answers (1)

sbolel
sbolel

Reputation: 3526

I think I can help here. First, a few things:

  • I'm assuming your getItem() doesn't use .$getRecord() and therefore someItem doesn't have an $id property. So, the properties of someItem get set as the properties of $scope.items.
  • You can .$add(someItem) to itemsArray if you want to create a new item.
  • You could use $scope.items.$save(someItem) if someItem has an $id.

Code

var ref = new Firebase(fbUrl+'/items');
itemsList = $firebaseArray(ref);
$scope.items = itemsList;

$scope.addItemObject = function() {
  var someItem = {};
  someItem.newField = 'test';
  itemsList.$add(someItem);
  console.log('$scope.items is',$scope.items);
}

$scope.updateItem = function() {
  console.log('$scope.items was',$scope.items);
  var id = prompt("Enter $id to update");
  var someItem = itemsList.$getRecord(id);
  var newField = prompt('Enter new value for newField');
  someItem.newField = newField;
  itemsList.$save(someItem).then(function(ref) {
    console.log('$scope.items is now',$scope.items);
  });;
}

Example

  • See this working PLNKR example
  • I created ItemsFactory in the PLNKR, which achieves the same result as the code above.

Documentation

Take a look at:

Hope that helps!

Upvotes: 9

Related Questions