angularjstwitter-bootstrapradio-buttonangularjs-ng-repeatsegmentedcontrol

Radio button deselects itself on clicking anywhere on the page


I am trying to implement segmented control button instead of normal radio button in Angular Although If i remove CSS class, normal radio button is working fine and remain selected on navigating to another page os clicking anywhere on the same page, but after adding CSS, radio button selection do not remain intact and deselects.

Please help with this

HTML Code :

<div class ="segmented-control">
            <div ng-repeat="p in LP">
                <a href="#" class="list-group-item">
                    <label> {{p.label}}
                        <input type ="radio" ng-model="test" name="test" value="{{p.value}}" ng-click="getElement($event)"></label>
                </a>
            </div>
          </div>

CSS :

.segmented-control input[type="radio"] {
    visibility:hidden;
}

.segmented-control .list-group-item {
    display: inline-block;
}

In controller.js calling below function to get the value of radio button

$scope.getElement= function(obj){

$scope.test = obj.target.value;
}

Solution

  • There are 2 issues with your code:

    1. You have nested elements <div><a tag><label><radio></label> but the ng-model will be set only when you click exactly on the label. If you click little outside the label the ng-model will not be updated.
    2. The gray color change that you see when you click on the segmented button does not mean that the radio button is selected. It is applying the following bootstrap class a.list-group-item:focus which means the button is in focus. That is why when you click outside the button the color changes back to white.

    To solve this you have to add extra class to highlight the selected button and make sure your ng-model is updated no matter where the user clicks inside the div.

    I have created a sample jsfiddle to demonstrate both the issues. Good luck and welcome to Stackoverflow!