anitha anitha - 5 months ago 20
HTML Question

How to display the checked radio button value in angularJs

I need to display selected radio button in the response div,if no option is selected that div will disappear,I will be thankful to if anyone can help me.


View Code:


<body ng-app="QuestionDisplayModule">
<form>
<div ng-controller="QuestionDisplayController">
<div ng-repeat="q in questionsData" style="border:groove 1px green">
<h4 style="color: darkmagenta">{{q.QText}}</h4>
<p ng-repeat="a in q.answer1" style="color: cadetblue"><input type="radio" name="answers" ng-model="options" value="{{a.option1}}" ng-checked="optionselected(options)" />{{a.option1}}</p>
<div>your answer is :{{selectedoption}}</div>
</div>
</div>
</form>
</body>



Script Code:


<script src="~/Scripts/angular.min.js"></script>
<script>
var myApp = angular.module("QuestionDisplayModule", [])
.controller("QuestionDisplayController", function ($scope, $http, $log) {

$scope.optionselected = function (options)
{
$scope.selectedoption = options;
}
$http.get("displayQuestion").then(function(response)
{
$log.info(response);
$scope.questionsData = response.data;
})
})
</script>

Answer

You should use different name for each question otherwise you will can select only one option for all question and and should use different model for each question and no need to use ng-checked="optionselected(options)" to set selected option value because of you used ng-model.

you can try like this

<div ng-controller="QuestionDisplayController">
      <div ng-repeat="q in questionsData" style="border:groove 1px green">
        <h4 style="color: darkmagenta">{{q.QText}}</h4>
        <p ng-repeat="a in q.answer1" style="color: cadetblue">
          <input type="radio" name="answers+{{$parent.$index}}" ng-model="q.selectedAns" value="{{a.option1}}" />{{a.option1}}</p>
        <div ng-show="q.selectedAns">your answer is :{{q.selectedAns}}</div>
      </div>
    </div>

PLUNKER DEMO