frostbyte
frostbyte

Reputation: 93

AngularJS ng-repeat questions and init inputs with matching answer object

I am using an ng-repeat to repeat through questions provided by an ajax response and I need the ng-model of each question input to point to a separate answers array.

The question array looks like this

bookingQuestions: [
    0: {
        label: 'Any allergies?',
        type: 'text',
        id: 1234
    },
    1: {
        label: 'Names of attendees',
        type: 'text',
        id: 1235
    }
]

I create the answers array by looping through all the questions and pushing the id and an empty answerValue property into my empty bookingAnswers array. The answers array looks like this:

bookingAnswers: [
    0: {
        id: 1234,
        answerValue: ''
    },
    1: {
        id: 1235,
        answerValue: ''
    }
]

In the markup, I'm attempting to init the answerObj by getting the correct answer object to match the corresponding question.

<div class="question" ng-repeat="question in bookingQuestions">
    <label class="question-label" for="{{question.id}}">{{question.label}}
    </label>
    <input type="text" name="{{question.id}}" ng-model="answerObj"
           ng-init="answerObj = getAnswerObj(question)">
</div>

The JS function:

$scope.getAnswerObj = function(question) {
    angular.forEach(bookingAnswers, function(answer) {
        if(question.id === answer.id) {
            return answer.answerValue;
        }
    });
}

Even though the JS function successfully returns the correct object property, the ng-model isn't being updated to use it. How do I get this working?

Upvotes: 0

Views: 84

Answers (2)

georgeawg
georgeawg

Reputation: 48968

<div class="question" ng-repeat="question in bookingQuestions">
    <label class="question-label" for="{{question.id}}">{{question.label}}
    </label>
    ̶<̶i̶n̶p̶u̶t̶ ̶t̶y̶p̶e̶=̶"̶t̶e̶x̶t̶"̶ ̶n̶a̶m̶e̶=̶"̶{̶{̶q̶u̶e̶s̶t̶i̶o̶n̶.̶i̶d̶}̶}̶"̶ ̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶a̶n̶s̶w̶e̶r̶O̶b̶j̶"̶
    <input type="text" name="{{question.id}}" ng-model="answerObj.answerValue"
           ng-init="answerObj = getAnswerObj(question)" />
</div>
$scope.getAnswerObj = function(question) {
    angular.forEach(bookingAnswers, function(answer) {
        if(question.id === answer.id) {
            ̶r̶e̶t̶u̶r̶n̶ ̶a̶n̶s̶w̶e̶r̶.̶a̶n̶s̶w̶e̶r̶V̶a̶l̶u̶e̶;̶
            return answer;
        }
    });
}

Upvotes: 0

jSebesty&#233;n
jSebesty&#233;n

Reputation: 1806

You bind the ng-model of all your inputs to some answerObj meaning they all point to the same variable. Using $index you can access the index of the current iteration. So you could do something like this:

<input type=“text“ name="{{question.id}}"
       ng-model="bookingAnswers[$index].answerValue"> </div>

Upvotes: 1

Related Questions