mvargos
mvargos

Reputation: 55

Set initial bootstrap radio button in Angular

I found a plunkr courtesy of @user2789093 in question AngularJS: Radio buttons do not work with Bootstrap 3 and modified it some to reflect my issue: http://plnkr.co/edit/sBfSD2?p=info In angular, I don't think I am supposed to manipulate the DOM, so does anyone have any thoughts on how I could set the intial bootstrap3 radio button to checked without using jquery to check an ID of the inputs?

Upvotes: 1

Views: 3136

Answers (2)

steampowered
steampowered

Reputation: 12062

This directive sets the active class on a radio input's parent element when the model value equals the input value, and removes the active class otherwise.

/* Bs radio not setting active class on label because model changes too slowly
 * before $render() in bsRadio inside AngularStrap.  */
myAppDirectives.directive('bsRadioFix',[function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, controller){
            scope.$watch(attrs.ngModel, function(newVal, oldVal){
                elem.parent().toggleClass('active', newVal == attrs.value)
            })
        }
    }
}]);

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67296

Once you bind ng-model and set the value attribute correctly, the issue doesn't seem to be the value of the resulting radio button selection. It is only that the bootstrap labels expect an active class to be applied if the selection is made. So you can fix this by adding an ng-class to each selection:

    <div class="btn-group col-lg-3" data-toggle="buttons">
        <label class="btn btn-default" ng-class="{active: test.currentVal == 'true'}" ng-click="setTransactionDebit('true')">
            <input type="radio" value="true" ng-model="test.currentVal"></input>
            True
        </label>
        <label class="btn btn-default" ng-class="{active: test.currentVal == 'false'}" ng-click="setTransactionDebit('false')">
            <input type="radio" value="false" ng-model="test.currentVal"></input>
            False
        </label>
    </div>

Here is a working fork of your plunker.

Upvotes: 2

Related Questions