Binding checkbox values to respective arrays in angularjs -
i have form created @ run time using angularjs. form has 6 questions , question 1 answers radio buttons while rest of questions have checkbox answers.
form created
<form ng-controller="personalityctrl" ng-submit="submitinterests()"> <div ng-repeat="question in interestquestions.slice(0,1)" style="display: block;"> <br> <span style="float: left">{{question.question}}</span> <br /> <span ng-repeat="(key, value) in question.choices"> <input name="{{question.number}}" ng-click="addchoice(question.number, key,question.questiontype)" type="radio" value="{{key}}" required /> {{value}} </span> <br /> </div> <div ng-repeat="question in interestquestions.slice(1,6)" style="display: block;"> <br> <span style="float: left">{{question.question}}</span> <br /> <span ng-repeat="(key, value) in question.choices"> <input name="{{question.number}}" ng-click="addchoice(question.number, key,question.questiontype)" type="checkbox" value="{{key}}" /> {{value}} </span> <br /> </div> <input type="submit" value="submit"></input> </ng-form> my generated form looks
question : 1 0 0 0 0 0 (0 represents radio button) question : 2 o o o o o (o represents check box) question : 3 o o o o o (o represents check box) question : 4 o o o o o (o represents check box) and when submit form post data should of form
[{1:[list of answers]},{2:[list of answers]},{...},{...},{...},{...}] where 1,2 represents question number, while list of answers value of checkboxes.
my question how can save answer each question in separate array using angularjs.
currently doing (but not seems angular way).
var q1 = { questionnumber : 1, answer : new array() }; var q2 = { questionnumber : 2, answer : new array() }; var q3 = { questionnumber : 3, answer : new array() }; var q4 = { questionnumber : 4, answer : new array() }; var q5 = { questionnumber : 5, answer : new array() }; var q6 = { questionnumber : 6, answer : new array() }; var userinterestanswers = [ q1, q2, q3, q4, q5, q6 ]; var choicelist = new array(); $scope.addchoice = function(question, choice, questiontype) { switch (question) { case 1: q1.answer.push(choice); break; case 2: q2.answer.push(choice); break; case 3: q3.answer.push(choice); break; case 4: q4.answer.push(choice); break; case 5: q5.answer.push(choice); break; case 6: q6.answer.push(choice); break; default: }
how rewrite addchoice function this
$scope.addchoice = function (question, choice, questiontype) { userinterestanswers[question].answer.push(choice); } and if can add type field in foreach question, can use ng-switch display either checkboxes or radio buttons can merge 2 repeaters. try rewrite pattern
<div ng-repeat ... > <div ng-switch on "question.type"> <input ng-switch-when="multichoice" type="checkbox" ... > <input ng-switch-when="singlechoice" type="radio" ... > </div> </div>
Comments
Post a Comment