gpt4 book ai didi

javascript - 如何使用 AngularFire 将项目添加到列表中项目中的特定字典中?

转载 作者:行者123 更新时间:2023-11-28 01:07:00 25 4
gpt4 key购买 nike

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

如何才能在每次添加评论时同时保存之前的评论?

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中生成的数据结构 { Hello World 测试: {-JSQhsAnY5zhf0oVKfbb: {title: "nameA", comment:"第二条评论"}, -JSQhsAnY5zhf0oVKfbb:{标题:“nameB”,评论:“第二条评论”}} }

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

{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"})

最佳答案

您正在将评论保存到名为评论的字段中。相反,使用名为注释的列表并利用 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 。相反,请考虑将注释放在自己的路径中,将项目放在自己的路径中。

关于javascript - 如何使用 AngularFire 将项目添加到列表中项目中的特定字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24953082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com