我有两个嵌套的ng-repeat产生多个问题,每个问题包含一堆单选按钮。当没有为某个问题选择无线电时,我无法想出一种有效的方法来显示验证错误消息,并在用户点击选择时获得所有选择的选项
<ul>
<li ng-repeat="question in questionModel.questionaire">{{question.question}}
<span style = "color:red" ng-show = "!!!ANOTHER CONDITION HERE!!! && questionModel.submitClicked != false">Please choose an answer </span>
<ul>
<li ng-repeat="answer in question.answers">
<input type="radio"
ng-click="questionModel.handleChange(answer)"
value={{answer}}
name="radio_{{$parent.$index}}"
required>
{{answer}}
</li>
</ul>
</li>
</ul>
你怎么建议我接近这个?在ul
上使用getElementById然后检查所有子节点?虽然这听起来很麻烦,但很容易,我可以很容易地得到所有被检查的按钮。是否有更好的方法来处理验证错误消息?
如果所有单选按钮都在同一个问题上很容易,我可以在单选按钮上进行ng-model。
编辑:添加信息
控制器:
myApp.controller('questionController', function($scope, $http, toServer){
$scope.questionModel = {
questionaire: [],
submitClicked: false,
handleChange: function(ans){
console.log(ans);
},
submit: function(){
this.submitClicked = true;
console.log(JSON.stringify(this.questionaire));
}
}
toServer.get_All_Questions(function(response){
$scope.questionModel.questionaire = response;
});
})
我为ajax调用创建的服务:
//this service handle all the ajax call to server
myApp.factory('toServer', function($http){
return {
get_All_Questions: function(callback){
var url = "/health1/server/questions";
$http.get(url).success(function(response){
response.forEach(function(item){
item.answers = (item.answers != null) ? item.answers.split(",") : [];
item.answered = false;
});
callback(response);
}).error(function(response){
console.log("error " + response)
});
}
}
});
[{id: "1", question: "what's your name?", answers: ["tom", "mary"]},
{id: "2", question: "what's your age?", answers: [1, 2]}
]
答案 0 :(得分:1)
很容易 - 使用ng-model
单选按钮:
<ul>
<li ng-repeat="question in questionModel.questionaire" {{question.question}}
<span style = "color:red" ng-show="!question.selectedAnswer && questionModel.submitClicked">Please choose an answer</span>
<ul>
<li ng-repeat="answer in question.answers">
<input type="radio"
ng-model="question.selectedAnswer"
ng-click="questionModel.handleChange(answer)"
value={{answer}}
name="radio_{{$parent.$index}}">
{{answer}}
</li>
</ul>
</li>
</ul>
答案 1 :(得分:1)
没有财产可以确认问题是否得到了回答。因此,我努力创建isAnswered = true/false
这样的属性,并在默认情况下将其初始化为false。
angular.forEach($scope.questionModel.questionaire, function(ques) {
ques.isAnswered = false;
return ques;
});
选择答案后,功能handleChange
会设置isAnswered = true
。
handleChange: function(ans, ques){
ques.isAnswered = true;
console.log(ques);
},
最后,在提交点击时,条件会检查是否点击了提交,如果有任何问题未得到回复,则会显示以下消息:
<span style = "color:red"
ng-show = "questionModel.submitClicked && !question.isAnswered">
Please choose an answer
</span>