Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS ng使用匹配的答案对象重复问题和初始输入_Javascript_Angularjs - Fatal编程技术网

Javascript AngularJS ng使用匹配的答案对象重复问题和初始输入

Javascript AngularJS ng使用匹配的答案对象重复问题和初始输入,javascript,angularjs,Javascript,Angularjs,我使用ng repeat来重复ajax响应提供的问题,我需要每个问题输入的ng模型指向一个单独的答案数组 问题数组如下所示 bookingQuestions: [ 0: { label: 'Any allergies?', type: 'text', id: 1234 }, 1: { label: 'Names of attendees', type: 'text', id:

我使用ng repeat来重复ajax响应提供的问题,我需要每个问题输入的ng模型指向一个单独的答案数组

问题数组如下所示

bookingQuestions: [
    0: {
        label: 'Any allergies?',
        type: 'text',
        id: 1234
    },
    1: {
        label: 'Names of attendees',
        type: 'text',
        id: 1235
    }
]
我通过循环所有问题并将id和一个空的answerValue属性放入我的空bookingAnswers数组来创建答案数组。答案数组如下所示:

bookingAnswers: [
    0: {
        id: 1234,
        answerValue: ''
    },
    1: {
        id: 1235,
        answerValue: ''
    }
]
<input type=“text“ name="{{question.id}}"
       ng-model="bookingAnswers[$index].answerValue"> </div>
在标记中,我试图通过获得与相应问题匹配的正确答案对象来初始化answerObj

<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>

即使JS函数成功地返回了正确的对象属性,ng模型也没有更新以使用它。如何使其工作?

将所有输入的ng模型绑定到某个answerObj,这意味着它们都指向同一个变量。使用$index可以访问当前迭代的索引。所以你可以这样做:

bookingAnswers: [
    0: {
        id: 1234,
        answerValue: ''
    },
    1: {
        id: 1235,
        answerValue: ''
    }
]
<input type=“text“ name="{{question.id}}"
       ng-model="bookingAnswers[$index].answerValue"> </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;
        }
    });
}