Fynn
Fynn

Reputation: 4873

Bootstrap radios in ng-repeat

I am using bootstraps radio buttons inside of an ng-repeat directive. However, the changes are not propagated to the underlying model. This is the code:

  <a href="#" class="btn btn-primary" ng-click="data.list.push({ value: 1 })">Add Item</a>
  <div class="alert alert-info">
    <div ng-repeat="item in data.list track by $index">
      <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-sm btn-default"><input type="radio" data-ng-model="item.value" value="1">1</label>
        <label class="btn btn-sm btn-default"><input type="radio" data-ng-model="item.value" value="2">2</label>
      </div> {{ item.value }}
    </div>
  </div>

The same example is working, as soon as I remove the button group and replace it with ordinary radio buttons like this:

  <a href="#" class="btn btn-primary" ng-click="data2.list.push({ value: 1 })">Add Item</a>
  <div class="alert alert-info">
    <div ng-repeat="item in data2.list track by $index">
      <input type="radio" data-ng-model="item.value" value="1">
      <input type="radio" data-ng-model="item.value" value="2">
      {{ item.value }}
    </div>
  </div>

I have setup a plunkr: http://plnkr.co/edit/ROLW8lluX6DrM3w2UUlH?p=preview

Upvotes: 1

Views: 388

Answers (2)

sebastian_oe
sebastian_oe

Reputation: 7320

This line (from your plunker) is the problem:

<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

The Bootstrap JS catches the click event on the wrapping label before AngularJS can register it on the radio input. Removing the bootstrap JS from your code fixes the problem (or at least works around it).

In general, it can become problematic to use the Bootstrap JS together with AngularJS.

Instead, consider using the AngularUI Bootstrap library instead. It also provides implementations for radio inputs masked as buttons, as well as some other Bootstrap JS-related functionality.

Upvotes: 1

lyschoening
lyschoening

Reputation: 18738

The Javascript doesn't actually change the values of the radio buttons; it just toggles the active class of the buttons that mask the radio buttons.

Consider using the button directive from AngularUI Bootstrap.

Upvotes: 1

Related Questions