【问题标题】:ngRepeat doesn't loop an arrayngRepeat 不循环数组
【发布时间】:2014-12-28 16:04:33
【问题描述】:

我有这个对象:

{
    "_id" : ObjectId("5454e173cf8472d44e7df161"),
    "questionType" : 0,
    "question" : "question1",
    "answers" : [ 
        {
            "content" : "answer1"
        }, 
        {
            "is_true" : "true",
            "content" : "answer2"
        }, 
        {
            "content" : "answer3"
        }
    ],
    "matches" : [],
    "__v" : 0
}

还有这个控制器:

var questionIndexController = function ($scope, Question, $routeParams) {
    var question = Question.get({id: $routeParams.id});
    $scope.question = question;
};


angular.module("adminMain")
    .controller("questionIndexController", ["$scope", "Question", "$routeParams", questionIndexController]);

还有这个标记:

<h3>Question:</h3>
<p>{{ question.question }}</p>
<ul>
    <li np-repeat="answer in question.answers">
        <span ng-show="answer.is_true">✓</span>
        <span>{{ answer.content }}</span>
    </li>
</ul>

但不幸的是,生成的 html 不包含来自 JSON 的任何答案。这意味着ngRepeat 没有循环通过question.answers 数组。

<div ng-view="" class="ng-scope"><h3 class="ng-scope">Question:</h3>
<p class="ng-binding ng-scope">question1</p>
<ul class="ng-scope">
    <li np-repeat="answer in question.answers">
        <span ng-show="answer.is_true" class="ng-hide">✓</span>
        <span class="ng-binding"></span>
    </li>
</ul>
</div>

知道如何解决这个问题吗?


编辑

这是问题工厂代码:

var questionFactory = function($resource, restUrls) {
    return $resource(restUrls.question.index, {}, {
        save: {
            url: restUrls.question.add,
            method: "POST",
            isArray: false
        }
    });
};

angular.module("adminMain").factory("Question", ["$resource", "restUrls", questionFactory]);

其中restUrls.question.index"/api/questions/:id"

以及获取单个问题的 node.js 后端代码:

function indexQuestions(req, res, next) {
    var questionId = req.params.id || null;
    if(!questionId) next(errorHandler(404, "Not found"));
    Question.findOne({ _id: questionId }, function(err, question) {
        if(err) return next(err);
        if(question.length === 0) return next(errorHandler(404, "Question not found"));
        res.json(question);
    });
}

当我从$resource 方法返回的console.log(question) 时,我得到一个普通的promise 对象:

【问题讨论】:

  • Question.get 返回什么?能否展示一下 Question.get 方法的代码?
  • @MichalCharemza 完成,请再次检查问题。
  • 你能 steup plunkr.. 我真的看不出代码有任何问题...

标签: javascript json angularjs node.js mongodb


【解决方案1】:

有错别字:

<h3>Question:</h3>
<p>{{ question.question }}</p>
<ul>
    <li np-repeat="answer in question.answers">
        <span ng-show="answer.is_true">✓</span>
        <span>{{ answer.content }}</span>
    </li>
</ul>

应该有ng-repeat 而不是np-repeate

【讨论】:

  • 哇哦!注意到这一点真是令人尴尬和令人印象深刻!当然也解决了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多