You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS问卷问题分组与ng-model区分绑定技术问询

Alright, let's build this grouped questionnaire with AngularJS where each radio button gets its own unique ng-model to track selections. I'll walk you through the complete setup, including data structure, controller logic, and the HTML template:

1. Define Your Grouped Questionnaire Data (JSON)

First, structure your JSON to include question groups, each containing multiple questions and their options. This makes it easy to loop through in the template:

{
  "questionGroups": [
    {
      "groupId": "group1",
      "groupTitle": "Personal Information",
      "questions": [
        {
          "questionId": "q1",
          "questionText": "What's your age range?",
          "options": [
            {"value": "18-25", "label": "18-25"},
            {"value": "26-35", "label": "26-35"},
            {"value": "36+", "label": "36+"}
          ]
        },
        {
          "questionId": "q2",
          "questionText": "What's your gender?",
          "options": [
            {"value": "male", "label": "Male"},
            {"value": "female", "label": "Female"},
            {"value": "other", "label": "Other"}
          ]
        }
      ]
    },
    {
      "groupId": "group2",
      "groupTitle": "Preferences",
      "questions": [
        {
          "questionId": "q3",
          "questionText": "Which device do you use most?",
          "options": [
            {"value": "mobile", "label": "Mobile Phone"},
            {"value": "desktop", "label": "Desktop"},
            {"value": "tablet", "label": "Tablet"}
          ]
        }
      ]
    }
  ]
}
2. AngularJS Controller Logic

In your controller, load the questionnaire data and initialize an object to store the selected answers. We'll use the questionId as the key for each selection to ensure unique ng-models:

angular.module('questionnaireApp', [])
.controller('QuestionnaireController', function($scope) {
  // Load your questionnaire data (could also come from an API)
  $scope.questionnaire = {
    "questionGroups": [
      // Paste the JSON data above here
    ]
  };

  // Initialize empty object to hold selected answers
  $scope.selectedAnswers = {};

  // Function to submit or process results
  $scope.submitAnswers = function() {
    console.log('Selected Answers:', $scope.selectedAnswers);
    // Add your submission logic here (e.g., send to server via $http)
  };
});
3. HTML Template Implementation

Use nested ng-repeat to loop through groups and questions. For each radio button, bind ng-model to selectedAnswers[question.questionId]—this ensures each question has its own unique model:

<div ng-app="questionnaireApp" ng-controller="QuestionnaireController">
  <!-- Loop through each question group -->
  <div ng-repeat="group in questionnaire.questionGroups" class="question-group">
    <h2>{{ group.groupTitle }}</h2>
    
    <!-- Loop through each question in the group -->
    <div ng-repeat="question in group.questions" class="question">
      <p><strong>{{ question.questionText }}</strong></p>
      
      <!-- Loop through each option for the question -->
      <div ng-repeat="option in question.options" class="option">
        <input 
          type="radio" 
          id="{{ question.questionId }}-{{ option.value }}"
          name="{{ question.questionId }}"
          ng-model="selectedAnswers[question.questionId]"
          ng-value="option.value"
        >
        <label for="{{ question.questionId }}-{{ option.value }}">{{ option.label }}</label>
      </div>
    </div>
  </div>

  <!-- Submit Button -->
  <button ng-click="submitAnswers()">Submit Questionnaire</button>

  <!-- Optional: Display Selected Answers for Testing -->
  <div class="results" ng-if="Object.keys(selectedAnswers).length > 0">
    <h3>Your Selected Answers:</h3>
    <ul>
      <li ng-repeat="(questionId, answer) in selectedAnswers">
        <strong>Question {{ questionId }}:</strong> {{ answer }}
      </li>
    </ul>
  </div>
</div>
Key Notes to Make This Work
  • Unique ng-model Binding: By using selectedAnswers[question.questionId], each question gets a distinct entry in the selectedAnswers object. This avoids conflicts between questions even if they have similar option values.
  • Radio Button Name Attribute: The name attribute is set to question.questionId to ensure that only one option per question can be selected (standard radio button behavior).
  • Dynamic IDs: The id and for attributes use a combination of questionId and option.value to make them unique across the entire form.
  • Processing Results: The submitAnswers function logs the selected answers, but you can extend it to send the data to a backend API using AngularJS's $http service.

内容的提问来源于stack exchange,提问作者rodrigo.rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:49:16