【问题标题】:How can I use ng-repeat to display data stored inside a nested object?如何使用 ng-repeat 显示存储在嵌套对象中的数据?
【发布时间】:2014-07-22 01:46:39
【问题描述】:

我正在处理包含嵌套数据的文档。我已经弄清楚如何存储嵌套数据(例如,与帖子关联的 cmets),但我不知道如何在查询中访问该数据。这是我所拥有的:

Node.js

app.get('post/:post_id/comments', function(req, res) {
    var Post = require('./models/post');
    Post.find(
        {_id: req.params.post_id},
        null,
        {},
        function (err, data) {
            if (err) return console.error(err);
            return res.json(data);
        }
    );
});

猫鼬:

var mongoose = require('mongoose');

var postSchema = mongoose.Schema({
    name : String,
    post : String,
    comments : [{
        name : String,
        text : String
    }]
});

module.exports = mongoose.model('Posts', postSchema);

AngularJS:

$scope.getPostComments = function(postID){
    $http({
        url: 'post/'+postID+'/comments',
        method: "GET"
    })
        .success(function (data, status, headers, config) {
            $scope.comments = data.comments;
            console.log(data.comments); // shows "undefined" in the console
        })
        .error(function (data, status, headers, config) {
            $scope.status = status;
        });
};

HTML:

<div ng-repeat="comment in comments">
    {{comment.name}}<br>
    {{comment.text}}
</div>

问题似乎出在$scope.comments = data.comments; 中,但我可以弄清楚如何解决它,以便ng-repeat 将显示我的 cmets(而不仅仅是空白)。有什么想法吗?

【问题讨论】:

  • 如果您使用console.log(data) 而不是console.log(data.comments),您会得到什么?
  • console.log(data) 将显示“[object Object]”,但我现在仍然确定如何访问 ng-repeat 指令中的数据。
  • $scope.data = data 添加到您的成功函数中,并将{{data}} 添加到您的视图某处(在ng-repeat 之外),并告诉我们它的样子。
  • 这是我在$scope.data = data 的控制台中得到的:“[{”__v”:0,”_id”:”36492070a8hm2a8j7f5fof6s”,”name”:”Joe Blow”,”post” :”这是一篇文章”,”cmets”:[{“name”:”Big Bird”,”text”:”这是一条评论。”}]]"

标签: node.js angularjs mongoose


【解决方案1】:

正确的解决方案是对返回的数据使用以下内容:

$scope.comments = data[0].comments;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多