Question

Here is the relevant code in my view:

p(ng-repeat="t in todos")
input(
    type="checkbox",
    ng-model="t.done",
    ng-click="clearItem($event)"
    )
{{t.text}} done? {{t.done}}

When the checkbox is clicked, I want the appropriate object in the todos array to be removed from the database.

My clearItem function is as follows:

$scope.clearItem = function(event) {
        todoRef.remove($scope.t);
    }

However, this removes all the entries in my database. I want it to remove only the specific object in question. Is there anyway for me to do this?

Was it helpful?

Solution

Ok, figured it out.

When looping using ng-repeat, use (id, t) in todos. This allows you to send id as the parameter to the ng-click function, and $scope.todos.$remove(id) works just fine.

OTHER TIPS

To provide a more complete example for anyone else that lands here, according to Firebase's documentation for AngularFire this would be the preferred way, and I believe the easiest way to remove an object:

// Create an app. Synch a Firebase array inside a controller
var myApp = angular.module("myApp", ["firebase"]);

// inject $firebaseArray 
myApp.controller("TodoCtrl", ["$scope", "$firebaseArray", function($scope, $firebaseArray) {

  // bind $scope.todos to Firebase database
  $scope.todos = $firebaseArray(myFirebaseRef.child("todo"));

  // create a destroy function
  $scope.removeTodo = function(todo) {
    $scope.todos.$remove(todo); 
  };
}]);

In your view, you could do something like below. Note that you could bind the removeTodo function to a checkbox as the question specifies, or a regular old <a href> element:

// In your view
<div ng-controller="TodoCtrl">
  <ul>
    <li ng-repeat="todo in todos">
      {{ todo.text }} : <a href ng-click="removeTodo(todo)">X</a>
    </li>
  </ul> 
</div>

Hope that helps!

A better solution would be to have $scope.clearItem() take the object t as an argument, instead of $event.

HTML - <p ng-repeat="t in todos"><input... ng-click="clearItem(t)">

JS - $scope.clearItem = function(obj) {todoRef.$remove(obj)};

The only way I'm able to remove the item is using a loop on the array we get from firebase.

var ref= new Firebase('https://Yourapp.firebaseio.com/YourObjectName');
var arr_ref=$firebaseArray(ref);
    for(var i=0;i<arr_ref.length;i++){
        if(key==arr_ref[i].$id){
            console.log(arr_ref[i]);
            arr_ref.$remove(i);
        }
    }

The easiest way to remove the object would be

scope.clearItem = function(event) {
  todoRef.$loaded().then(function(){
   todoRef.$remove($scope.t)
 });

The asynchronous nature of the beast has gotten me a few times.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top