Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Item from Firebase

I'm trying to understand how to remove an item from my Firebase. I've set up a function (createProvider) to create an item , but can't figure out how to go about removing 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've got as far as creating a function called removeProvider but can't work out what to put inside it. I realise I've got to somehow target the particular item and then remove it from the list. I'm just not sure how.

Any help with this would be appreciated. Thanks in advance!

like image 626
realph Avatar asked Dec 03 '25 17:12

realph


1 Answers

To remove an item from Firebase, you will need to know its name(), which is automatically generated for you when you call push() to add a new item to Firebase.

So you will need to bind the name to the scope:

$scope.providers.push({
  name: snapshot.name(),
  title: snapshotVal.title
});

You then pass this name into your call to 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 on 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 $asArray() method).

like image 76
Frank van Puffelen Avatar answered Dec 06 '25 08:12

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!