puneeth8994 puneeth8994 - 1 month ago 6
Javascript Question

How to iterate through a property in object within an array in Angular?

In AngularJs, I'm using ng-repeat option to display

questionText
property inside each object in an array.

[{
"_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"
}]


The above is the array that I'm trying to go through.

This is my HTML code for the
ng-repeat
.

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


It just iterates through the object in the first index 5 times. How do I make it iterate through each object?
I tried
viewQuestions.questions.questionText
and
viewQuestions.questions[].questionText

Neither of it is working.

Answer

questionText property value would be displayed like the below in ng-repeat ,where questionText in ng-repeat will represent object in questions list

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

You should rename the questionText in ng-repeat to like question so each repeated div will represent a question in questions list/array.

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

ng-repeat expression -

ng-repeat="variable in expression"

where variable is the user defined loop variable and expression is a scope expression giving the collection to enumerate. Read more here - https://docs.angularjs.org/api/ng/directive/ngRepeat

Comments