如何遍历Angular中数组中对象的属性?

时间:2016-10-10 07:39:18

标签: javascript angularjs arrays html5

在AngularJs中,我使用ng-repeat选项在数组中的每个对象中显示questionText属性。

[{
    "_id": "57fa2df95010362edb8ce504",
    "__v": 0,
    "answers": [],
    "options": [],
    "questionText": "what is your name?,What is your qualification?,Which city do you reside in?",
    "questionId": "H1Mb0jPA",
    "surveyId": "ryVj6Pf0"
}, {
    "_id": "57fa441e5010362edb8ce507",
    "__v": 4,
    "answers": [],
    "options": ["BE", "MBA", "MS", "MTech"],
    "questionText": "What is your degree name?",
    "questionId": "BJPQ46vC",
    "surveyId": "ryVj6Pf0"
}, {
    "_id": "57fa6fb65010362edb8ce509",
    "__v": 0,
    "answers": [],
    "options": [],
    "questionText": "Which city do you live in?",
    "questionId": "ryA2Jgd0",
    "surveyId": "ryVj6Pf0"
}, {
    "_id": "57fa70125010362edb8ce50a",
    "__v": 0,
    "answers": [],
    "options": [],
    "questionText": "Have you tried this product?",
    "questionId": "BJqGlxOR",
    "surveyId": "ryVj6Pf0"
}, {
    "_id": "57fa71085010362edb8ce50b",
    "__v": 0,
    "answers": [],
    "options": [],
    "questionText": "wassup?",
    "questionId": "H1WMbluC",
    "surveyId": "ryVj6Pf0"
}]

以上是我试图通过的数组。

这是我ng-repeat的HTML代码。

<div ng-controller="viewQuestionController as viewQuestions">
    <div ng-repeat="questionText in viewQuestions.questions">
        <h2>{{viewQuestions.questions[0].questionText}}</h2>
    </div>
</div>

它只是在第一个索引中遍历对象5次。如何让它遍历每个对象? 我试过了viewQuestions.questions.questionTextviewQuestions.questions[].questionText 它们都没有用。

1 个答案:

答案 0 :(得分:2)

questionText属性值将在ng-repeat中显示如下,其中ng-repeat中的questionText将表示问题列表中的对象

<div ng-controller="viewQuestionController as viewQuestions">
<div ng-repeat="questionText in viewQuestions.questions">
    <h2>{{questionText.questionText}}</h2>
</div>

您应该将ng-repeat中的questionText重命名为类似问题,以便每个重复的div代表问题列表/数组中的问题。

<div ng-controller="viewQuestionController as viewQuestions">
<div ng-repeat="question in viewQuestions.questions">
    <h2>{{question.questionText}}</h2>
</div>

ng-repeat表达式 -

ng-repeat="variable in expression"

其中variable是用户定义的循环变量,expression是一个范围表达式,用于枚举集合。 在此处阅读更多内容 - https://docs.angularjs.org/api/ng/directive/ngRepeat