I have a form
with only radio
buttons, the form
must be validated before submission (user must select something). After user selects a radio button some styling should apply using ngclass
. I have two problems:
1. For some reason the last option is selected by default.
2. I am not able to get form validation attributes. The data is not refreshed when I select stuff on it.
JS:
app.controller('MainCtrl', function($scope) {
$scope.questionObject = [{
"body": "abc"
}, {
"body": "def"
}, {
"body": "aghi"
} ]
$scope.selectAnswer=function(number,obj)
{
$scope.isChecked=number;
}
});
HTML:
<div class="form-group" ng-form="form">
<div class="col-lg-8 col-lg-offset-2 col-sm-12">
<div class="row" ng-repeat="obj in questionObject track by $index">
<div class="radio">
<label class="choice" ng-class="{'choiceSelected': isChecked==$index}">
<input type="radio"
name="optradio"
ng-click="selectAnswer($index,questionObject.correct_answer)"
ng-model="radioInput">{{obj.body}}
</label>
</div>
</div>
</div>
</div>
<pre>
dirty:{{form.$dirty}}
pristine:{{form.$pristine}}
</pre>
EDIT This is the form output. Never gets updated
{
"$error": {},
"$name": "form",
"$dirty": false,
"$pristine": true,
"$valid": true,
"$invalid": false,
"$submitted": false
}
Try like this. look for the ng-model and ng-required attributes for radio button.
<div name="myForm" novalidate ng-form>
<div class="col-lg-8 col-lg-offset-2 col-sm-12">
<div class="row" ng-repeat="obj in questionObject track by $index">
<div class="radio">
<label class="choice" ng-class="{'choiceSelected': isChecked==$index}">
<input type="radio" name="optradio" ng-click="selectAnswer($index,questionObject.correct_answer)" ng-model="data.option" ng-value="obj.body" ng-required="data.option == ''">{{obj.body}}
</label>
</div>
</div>
</div>
</div>
<pre>
dirty:{{myForm.$dirty}}
pristine:{{myForm.$pristine}}
$valid:{{myForm.$valid}}
$invalid:{{myForm.$invalid}}
</pre>
Plunker :https://plnkr.co/edit/crpV5QnSGdSv6rUBnTnR?p=preview