2014-03-19 60 views
5

这在我看来是相关代码:AngularFire - 删除单个项目

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

当点击复选框,我想todos数组中的相应对象从数据库中删除。

clearItem功能如下:

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

然而,这消除在我的数据库中的所有条目。我希望它只删除有问题的特定对象。无论如何对我来说这样做?

回答

8

好吧,算出来。

当使用ng-repeat循环时,请使用(id, t) in todos。这使您可以将id作为参数发送给ng-click函数,而$scope.todos.$remove(id)可以正常工作。

1

更好的解决方案是让$scope.clearItem()将对象t作为参数,而不是$event

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

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

1

我能够删除该项目是利用我们的火力得到阵列上的循环的唯一方法。

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); 
     } 
    } 
+0

slfan立即检查出来 –

0

删除对象的最简单的方法是

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

兽的异步特性已经得到了我几次。

4

为了给其他任何人登陆这里更完整的示例,根据Firebase's documentation for AngularFire这将是首选的方式,我相信最简单的方法来删除对象:

// 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); 
    }; 
}]); 

在你看来,你可以做下面的事情。需要注意的是,你可以绑定removeTodo功能复选框为问题指定,或者一个普通的旧<a href>元素:

// 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> 

希望帮助!