【问题标题】:How to add items to a specific dictionary within an item in a list with AngularFire?如何使用AngularFire将项目添加到列表中的项目中的特定字典?
【发布时间】:2014-09-17 03:38:46
【问题描述】:

以下代码显示了来自 firebase 的列表,并为列表中的每个项目显示了相应的评论字段。用户可以对该项目发表评论,它将更新列表中该项目的评论字段。目前,每次发表评论时,都会覆盖之前的评论,但我希望保存所有 cmets。

我如何做到这样每次添加评论时,以前的评论也会被保存?

http://jsfiddle.net/chrisguzman/PS9J2/

indx.html

<div ng-app="MyApp" ng-controller="MyCtrl">
    <div ng-repeat="(id,item) in data">
         <h2>{{item.title}}</h2>

        <input ng-model="item.comment"></input>
        <button type="submit" ng-click="CommentAdd(id)">Comment</button>
    </div>
</div>

app.js

angular.module('MyApp', ['firebase'])
    .controller('MyCtrl',

function MyCtrl($scope, $firebase) {
    var furl = "https://helloworldtest.firebaseio.com";
    var ref = new Firebase(furl);
    $scope.data = $firebase(ref);

    $scope.CommentAdd = function (id) {
        $scope.data.$save(id);
    };

});

以下是firebase中生成的数据结构 {你好世界测试: {-JSQhsAnY5zhf0oVKfbb: {title: "nameA", comment:"Second Comment"}, -JSQhsAnY5zhf0oVKfbb:{标题:“nameB”,评论:“第二条评论”}} }

但是,我想创建以下内容,其中有一个包含所有 cmets 的“cmets”分支。

{helloworldtest: 
{-JSQhsAnY5zhf0oVKfbb: {title: "nameA", comments:{-JSQhsAnY5zhf0oVKfbb:{Comment:"Second Comment"},-JSQhsAnY5zhf0oVKfbb:{Comment:"First Comment"}}},
{-JSQhsAnYdfdfdffbb: {title: "nameA", comments:{-JSQhsAnY5zhf0oVKfAb:{Comment:"Another Comment"},-JSQhsAnY5zhf0oVKfbb:{Comment:"First Comment"}}}
}

我试图通过替换来做到这一点

$scope.data.$save(id);

$scope.data.$add(id);

我也试过使用:

$scope.data[id].$add({foo: "bar"})

【问题讨论】:

    标签: javascript html angularjs firebase angularfire


    【解决方案1】:

    您正在将评论保存到名为评论的字段中。相反,请使用名为 cmets 的列表并使用 push$add

    <div ng-app="MyApp" ng-controller="MyCtrl">
        <div ng-repeat="(id,item) in data">
             <h2>{{item.title}}</h2>
    
            <input ng-model="newComment"></input>
            <button type="submit" ng-click="addComment(id, newComment)">Comment</button>
        </div>
    </div>
    
    function MyCtrl($scope, $firebase) {
        var furl = "https://helloworldtest.firebaseio.com";
        var ref = new Firebase(furl+'/items');
        $scope.data = $firebase(ref);
    
        var $comments = $firebase( commentsRef );
    
        $scope.addComment = function (id, newComment) {
           ref.child(id).child('comments').push(newComment);
        };
    
    });
    

    还有Don't nest data just because you can。相反,请考虑将 cmets 放在自己的路径中,将项目放在自己的路径中。

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 2021-07-02
      • 2020-08-19
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多