2014-07-25 36 views
1

下面的代碼顯示了來自firebase的列表,並顯示了列表中每個項目的相應註釋字段。用戶可以對該項目發表評論,並且會更新列表中該項目的評論字段。目前,每次發表評論時,都會覆蓋前一個評論,但我想要保存所有評論。如何使用AngularFire將項目添加到列表中項目中的特定字典?

如何讓每一個評論的添加,在以前的保存以及時間,以便?

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

}); 

下面是產生 {helloworldtest火力內的數據結構: { -J SQhsAnY5zhf0oVKfbb是:{title: 「NAMEA」 評論: 「二評」}, -JSQhsAnY5zhf0oVKfbb是:{title: 「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"}) 

回答

1

要保存該評論進入一個名爲評論的領域。相反,請使用名爲「評論」的列表並使用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。相反,可以考慮將評論放在他們自己的路徑中,將項目放在他們自己的路徑中

相關問題