Remove item from Firebase
I am trying to figure out how to remove an item from my Firebase. I've created a function ( createProvider
) to create an item, but can't figure out how to go about deleting an item.
Html
<form role="form" name="createProviderForm">
<input type="text" ng-model="title">
<button type="submit" ng-click="createProvider()">Submit</button>
</form>
<div ng-repeat="provider in providers">
<h3>{{ provider.title }}</h3>
<button type="button" ng-click="removeProvider()">Remove</button>
</div>
</div>
Js
var rootRef = new Firebase(FBURL);
var providersRef = rootRef.child('providers');
$scope.newProvider = {};
$scope.providers = [];
providersRef.on('child_added', function(snapshot) {
$timeout(function() {
var snapshotVal = snapshot.val();
console.log(snapshotVal);
$scope.providers.push({
title: snapshotVal.title
});
});
});
$scope.createProvider = function() {
var newProvider = {
title: $scope.title
};
providersRef.push(newProvider);
};
$scope.removeProvider = function() {
};
I got to creating a function called removeProvider
, but I can't figure out what to add to it. I understand that I need to target a specific element somehow and then remove it from the list. I just don't know how to do it.
Any help with this would be greatly appreciated. Thanks in advance!
source to share
To remove an item from Firebase you need to know it name()
, which is automatically generated for you when you call push()
to add a new item to Firebase.
So, you need to associate a name with a scope:
$scope.providers.push({
name: snapshot.name(),
title: snapshotVal.title
});
Then you pass this name to your call removeProvider
from your HTML:
<div ng-repeat="provider in providers">
<h3>{{ provider.title }}</h3>
<button type="button" ng-click="removeProvider(provider.name)">Remove</button>
</div>
And use it to call remove
in Firebase:
$scope.removeProvider = function(name) {
providersRef.child(name).remove();
};
As @SharpieOne already commented, this and many other things are automatically handled for you if you use the AngularFire library (and in this case specifically its method $asArray()
).
source to share