Reputation: 171
The following JSFiddle allows me to deselect a radio button selection.
http://jsfiddle.net/8s4m2e5e/132/
I'm using AngularJS 1.4 and in one of the posts here, I read that the above JSFiddle doesn't work with angular 1.3+ versions. Thats true, it doesn't work when I implemented the code in the above fiddle. How do I get this functionality to work with my version?
Following is my code.
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="@Model.FieldName"
name="@Model.FieldName"
ng-model="gPA(@Model.Id).value"
value="@((part as BaseInputPartVM).GetStringValue())"
ng-click="uncheck($event, @Model.Id)" />
</div>
}
In my controller,
$scope.uncheck = function (event, partId) {
if ($scope.gPA(partId).value == event.target.value)
$scope.gPA(partId).value = false
}
This code works for deselecting (uncheck) a radio button selection. However, the basic radio button selection doesn't work and I'm not able to select any radios, because the above if condition is always turning to true.
Is there a way I can check for the Previously selected radio value and the new selected value? In order to get the above functionality to work correctly, I need to access both the previous and new radio selected values for comparison. I've looked into ng-model, ng-change and all of them fetches the current radio selected value, but I also need to know the previous selected value as well.
Upvotes: 2
Views: 9119
Reputation: 171
Okay. I think I got an answer to my question... for the input radio, I added ng-mouseup event to capture the previous value of the radio selection before the click. Also, I've added a hidden variable on the page to store this previous radio button selected value. Then in the ng-click event, I will check the previous selected value against the current selected value. If previous and current values are same, I will set the value to null or false, to uncheck the selection.
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="@Model.FieldName"
name="@Model.FieldName"
ng-model="gPA(@Model.Id).value"
value="@((part as BaseInputPartVM).GetStringValue())"
ng-mouseup = "setPreviousSelectedValue(@Model.Id)"
ng-click="uncheck($event, @Model.Id)" />
</div>
}
<input type="hidden" id="previousRadioSelection" name="previousRadioSelection" ng-model="previousRadioSelection" value="" />
In the controller,
//set previous selected value of radio button
$scope.setPreviousSelectedValue = function (partId) {
$scope.previousRadioSelection = $scope.gPA(partId).value;
}
//uncheck radio button
$scope.uncheck = function (event, partId) {
if ($scope.previousRadioSelection == event.target.value)
$scope.gPA(partId).value = null;
}
Upvotes: 1