【问题标题】:AngularFire - Remove Single ItemAngularFire - 删除单个项目
【发布时间】:2014-04-25 02:50:37
【问题描述】:

这是我认为的相关代码:

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

但是,这会删除我数据库中的所有条目。我希望它只删除有问题的特定对象。反正我可以这样做吗?

【问题讨论】:

    标签: angularjs pug firebase angularfire


    【解决方案1】:

    好的,想通了。

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

    【讨论】:

      【解决方案2】:

      根据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>
      

      希望有帮助!

      【讨论】:

        【解决方案3】:

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

        HTML - &lt;p ng-repeat="t in todos"&gt;&lt;input... ng-click="clearItem(t)"&gt;

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

        【讨论】:

          【解决方案4】:

          我能够删除该项目的唯一方法是在我们从 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);
                  }
              }
          

          【讨论】:

          • slfan 立即查看
          【解决方案5】:

          删除对象的最简单方法是

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

          野兽的异步特性让我好几次了。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-06-02
            • 1970-01-01
            • 2016-04-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多