【问题标题】:AngularJS ng-repeat questions and init inputs with matching answer objectAngularJS ng-repeat 问题和具有匹配答案对象的初始化输入
【发布时间】:2019-03-04 03:56:45
【问题描述】:

我正在使用 ng-repeat 重复 ajax 响应提供的问题,我需要每个问题输入的 ng-model 指向一个单独的答案数组。

问题数组如下所示

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

我通过遍历所有问题并将 id 和一个空的 answerValue 属性推送到我的空 bookingAnswers 数组来创建答案数组。 answers 数组如下所示:

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

在标记中,我试图通过获取正确答案对象以匹配相应问题来初始化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函数:

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

即使 JS 函数成功地返回了正确的对象属性,ng-model 也没有被更新来使用它。我如何让它发挥作用?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      <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;
              }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2013-09-09
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多