Angular UI.Bootstrap's radio buttons act strange with ng-repeat

All we need is an easy explanation of the problem, so here it is.

I have a problem dynamically generating options for a radio model in angular’s ui.bootstrap. I thought I could simply ng-repeat over an array, using it’s contents for the btn-radio attribute like so:

//in the controller
$scope.radioModel =  undefined;
$scope.radioModelButtons = ["a", "b", "c"];

//in the html
<div class="btn-group" >
  <button ng-repeat="value in radioModelButtons"
    class="btn" type="button" ng-model="radioModel"
    btn-radio="'{{value}}'">
      {{value}}
  </button>
</div>

I’m using angular 1.1.4 and ui.bootstrap 0.3.0.

Here is a jsfiddle of my efforts, as you can see, the radio buttons act independently and do not affect the radioModel variable.

Thanks!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

This is how you should write your markup:

<button ng-repeat="value in radioModelButtons"
        class="btn" type="button" ng-model="radio.model"
        btn-radio="value">
          {{value}}
</button>

And the working jsFiddle: http://jsfiddle.net/yMLqz/2/

There were 2 problems in your approach:

  • btn-radio should be used with AngularJS expression, and not an interpolated value
  • ng-repeat is creating a new scope so you need to take this into account if you want to bind to a value defined on a parent scope

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply