Boxiom
Boxiom

Reputation: 2305

AngularJS - Ng-repeat with radio buttons and boolean value

I have an array of Book-objects, each with the boolean property Favorite. Only one of the books has Favorite set to true.

I'm displaying these books using ng-repeat, and I want to be able to set the favorite book with radio buttons. However, even though the correct radio button is selected upon page load, the model doesn't update the boolean values when I select a different radio button.

Here's my code:

<ul>
    <li ng-repeat="book in vm.Books">
        {{book.Name}}
        <input name="book" type="radio" ng-model="book.Favorite" ng-value="book.Favorite" /> 
    </li>
<ul>

How do I update the model with the correct Favorite-value based on the checked radio button?

Upvotes: 0

Views: 3109

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

The following is close, but will not set book.Favorite to false when you pick another one (which I assume you want?):

<li ng-repeat="book in vm.Books">
  {{book.Name}}
  <input name="book" type="radio" ng-model="book.Favorite" ng-value="true">
</li>

I would just go this way instead:

<li ng-repeat="book in vm.Books">
  {{book.Name}}
  <input type="radio" ng-click="vm.setFavorite(book)" ng-checked="book.Favorite">
</li>

And:

vm.setFavorite = function(book) {

  vm.Books.forEach(function(b) {
    b.Favorite = book === b;
  });
};

Demo: http://plnkr.co/edit/UKGQW1dd8M5UiEbUCxWd?p=preview

Upvotes: 4

Related Questions