Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  85] [ 7]  / answers: 1 / hits: 28397  / 10 Years ago, thu, july 3, 2014, 12:00:00

I can use the following to add an object to my Firebase data store:



var uniqueId = {
name: a name,
location: new york
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
// do something on success
}, function(){
// do something if call fails
});


The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned. The object I just added is saved under this key.



Is there a way for me to specify what the key name is when I add to my data store?


More From » angularjs

 Answers
17

Everything in Firebase is a URL.


Take the following URL for example.


https://myapp.firebaseio.com/users/

Let's say we want to create a user with a key of 1 as a child at this location. Our URL would look like this.


https://myapp.firebaseio.com/users/1

To create a user using AngularFire we can create a reference at the users node and call $child(1) to create a reference to that location.


var usersRef = new Firebase('https://myapp.firebaseio.com/users');
var userRef = new Firebase('https://myapp.firebaseio.com/user/1');

$scope.users = $firebase(usersRef);

// these are the same
$scope.userOne = $firebase(userRef);
$scope.userOne = $scope.users.$child(1);

Then we can use $set to store the value of the user at that location.


var usersRef = new Firebase('https://myapp.firebaseio.com/users');
$scope.users = $firebase(usersRef);
$scope.users.$child(1).set({
first: 'Vincent',
last: 'Van Gough',
ears: 1
});

In your case it would be:


var uniqueId = {
id: 1,
name: "a name",
location: "new york"
};
$scope.myItems.$child(uniqueId.id).$set(uniqueId);

Remember that using $set will destroy any previous data at that location. To non-destructively update the values use $update.


[#70329] Tuesday, July 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;