【发布时间】:2016-06-03 06:28:39
【问题描述】:
我有两个嵌套的 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)
});
}
}
});
$scope.questionModel.questionaire(来自服务器的响应)的结构是一个 json 数组:
[{id: "1", question: "what's your name?", answers: ["tom", "mary"]},
{id: "2", question: "what's your age?", answers: [1, 2]}
]
【问题讨论】:
-
!!question.answered? -
o 那只是一个变量,我正在玩弄它希望能想出一个解决方案
-
@LoremIpsum
questionModel.handleChange()做什么? -
另一个毫无意义的功能。它所做的只是打印出使用
console.log传递给handlechange 的参数
标签: angularjs