如何使用angularjs

时间:2017-09-07 09:55:49

标签: javascript angularjs json validation angularjs-ng-form

我有这个JSON数据,我有一些选项来构建表单,我正在尝试创建一个动态表单,每个屏幕每个问题以及next / prev按钮。这是我到目前为止所尝试的。有人可以帮我创建具有此JSON的表单以及表单验证和上一页/下一页功能吗?

Plunker:https://plnkr.co/edit/p2qVI7kqOnqoKjYr6yb3?p=preview

JSON

var questions = [
      {
        text: "What is your name?",
        type: "text",
        required: true,
        model: "name"
      },
      {
        text: "Tell us something about yourself.",
        type: "textarea",
        required: true,
        model: "about"
      },
      {
        text: "Explain your job profile",
        type: "textarea",
        required: false,
        model: "profile"
      },
      {
        text: "Which is the largest country in the world by population?",
        offeredAnswers: [
          {"value": "Yes"},
          {"value": "No"}
        ],
        type: "radio",
        required: true,
        model: "radio1"
      },
      {
        text: "Would you be available to work in shifts?",
        offeredAnswers: [
          {"value": "Yes"},
          {"value": "No"}
        ],
        type: "radio",
        required: true,
        model: "radio2"
      },
      {
        text: "How long have you been working at your current job?",
        offeredAnswers: [
          {"value": "Not long, it's part time"},
          {"value": "1-2 yrs"},
          {"value": "3-4 yrs"},
          {"value": "5+ yrs"}
        ],
        type: "radio",
        required: true,
        model: "radio3"
      }
];

HTML

<form name="mmSurvey">
   <ul id="options">
      <li ng-show="question">
         <label>
            <div ng-if="(question.type == 'radio' && question.options)">
               <p ng-repeat="option in question.options">
                  <input type="{{option.type}}" name="" ng-change="updateAnswerList(option.value)" ng-required="{{option.required}}" />
               </p>
            </div>
            <div ng-if="(question.type == 'text')">
               <input type="{{question.type}}" ng-required="{{question.required}}" />
               <!-- show an error if this isn't filled in -->
               <p ng-show="mmSurvey.mm.$error.required">Please enter your name.</p>
            </div>
            <div ng-if="(question.type == 'textarea')">
               <textarea ng-required="{{question.required}}"></textarea>
            </div>
         </label>
      </li>
   </ul>
</form>

1 个答案:

答案 0 :(得分:0)

嗯..假设你在询问上一个/下一个部分。

可以通过将当前问题分配给变量来完成。

//init
var currentIndex = 0;

//update question object according to index
$scope.$watch(function() {
  return currentIndex;
}, function() {
  $scope.question = questions[currentIndex];
});

$scope.next = function() {
  // validation here
  // hint: you can use formname.$invalid for first check

  // increase question number
  currentIndex++;
}

// similar for prev

顺便说一下,您应该在每个按钮中添加type="button",这样每次点击时都不会尝试提交表单。