0
votes

Okay, so I've got an angularfire app that sends text entries to firebase, but I'm having trouble writing the functions to delete them from firebase.

here is my HTML

<button class="btn btn-secondary" ng-click="deleteAll()">Remove All</button>

  <ul class="messages">
    <li ng-repeat="item in list" class="item panel">
      <h3>{{item.name}}</h3>
      <p>{{item.message}}</p>
      <button class="btn" ng-click="deleteThis()">Delete</button>
    </li>
  </ul>

deleteThis is meant to delete the single item the button is attached to and deleteAll is meant to delete all items.

var myApp = angular.module("myApp",["firebase"]);

myApp.controller("SampleCtrl", function($scope, $firebaseArray) {

  var list = $firebaseArray(new Firebase("https://writeup.firebaseio.com/"));

  $scope.list = list;

  $scope.submit = function(){
    var name = document.getElementById("name").value,
        message = document.getElementById("message").value;

            list.$add({ name: name, message: message }).then(function(ref) {
          var id = ref.key();
          list.$indexFor(id);
        });
  }

  $scope.deleteAll = function(){
    $scope.id.$remove();
  };

  $scope.deleteThis = function(id, name, message){
    $scope.list.$remove(id);
  }

});
2
You aren't passing anything into deleteThis(); not sure how you could expect this to work. - Kato

2 Answers

3
votes

In your HTML pass the item to the deleteThis function as an argument.

  <ul class="messages">
    <li ng-repeat="item in list" class="item panel">
      <h3>{{item.name}}</h3>
      <p>{{item.message}}</p>
      <button class="btn" ng-click="deleteThis(item)">Delete</button>
    </li>
  </ul>

In your controller use the argument.

$scope.deleteThis = function(item){
    $scope.list.$remove(item);
};

From the Docs:

$remove(recordOrIndex)

Remove a record from the database and from the local array. This method returns a promise that resolves after the record is deleted at the server. It will contain a Firebase reference to the deleted record. It accepts either an array index or a reference to an item that exists in the array.

-- AngularFire API Reference - $remove

1
votes

You cannot remove a record by its ID, only by its index or by passing the entire item into $remove().

The solution is to look up the index first and pass that into $remove():

$scope.list.$remove($scope.list.$indexFor(id))