【问题标题】:Get $id from nested ng-repeat从嵌套的 ng-repeat 中获取 $id
【发布时间】:2015-11-23 21:30:30
【问题描述】:

我在 Angularjs 和 Firebase 中有一个帖子/评论系统,我可以毫无问题地循环显示所有带有 ng-repeat 及其 cmets 的帖子。当我尝试从第二个嵌套的 ng-repeat 获取 $id 以便能够将回复保存到评论中时,问题就开始了。让我们看看我的代码:

<div class="posts" ng-repeat="post in posts">
  <div>{{post.text}}</div>
  <div>
    <input type="text" placeholder="Comment here..." ng-model="comment">
    <button ng-click="addComment(post, comment)"></button>
  </div>
  <div class="comments" ng-repeat="cmt in post.comments">
    <p>{{cmt.text}}</p>
    <div>
      <input type="text" ng-model="answer">
      <button ng-click="addAnswer(cmt, post)"></button>
    </div>
      <div ng-repeat="answer in cmt.answers">
      <p>{{answer.text}}</p>
      </div>
  </div> 
</div>

app.js

$scope.addComment = function(post, comment){

    var ref = new Firebase("https://url.firebaseio.com/users/" + post.$id + "/comments");

    var comments = $firebaseArray(ref);

    comments.$add({

    text: comment

   });

}

$scope.addAnswer = function(cmt, post){

        var refanswers = new Firebase("https://url.firebaseio.com/users/" + post.$id + "/comments/" + cmt.$id + "/answers");

        var answers = $firebaseArray(refanswers);

        answers.$add({

        text: answer

       });

    }

为了测试,首先我在 addAnswer 函数中删除上面的代码并编写两个 console.log 来检查我是否得到了值

console.log(post.$id);

console.log(cmt.$id);

我只得到 post.$id 但没有第二个(未定义),我错过了关于嵌套 ng-repeat 的一些内容吗?

已编辑:我根据以下答案更改了代码以避免 $scope 冲突,但仍然无法正常工作。

欢迎任何建议,谢谢:)

【问题讨论】:

    标签: javascript angularjs firebase angularfire


    【解决方案1】:

    comment 被传递到 addAnswer() 可能不是您所想的 ng-repeat 的实例对象,而是它可能与上面已经定义的 ng-model='comment' 发生冲突。你有一个范围问题。

    这可以通过将 ng-repeat="comment in post.comments" 更改为 ng-repeat="cmnt in post.comments" 或任何您想要的名称来解决,只要它不与之前定义的 $scope 对象冲突。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多