1

I have a collection, and I am looping over it.

<tbody>
    <tr ng-repeat="account in vm.pagedAccounts.items"
        ng-class="{ 'highlight': (account.rowIsSelected === account) }"
        <td>
            <input
                ng-model="account.rowIsSelected"
                ng-value="{{account}}"
                name="selectedAccount"
                ng-change="vm.selectAccount(account)"
                type="radio">
        </td>

ng-value is set to the entire account object. Now, the row is being highlighted but the button is not checked. In controller,

vm.selectAccount = function (account) {
    account.rowIsSelected = account;
}

What am I doing wrong?

StrugglingCoder
  • 4,781
  • 16
  • 69
  • 103

2 Answers2

1

I think this is what you are looking for. Instead of using ng-change its more commong to use a seperate selected model.

View

<div ng-controller="MyCtrl as vm">
  <table>
    <tbody>
      <tr ng-repeat="account in vm.items" 
          ng-class="{ 'highlight': account === vm.selected }">
        <td>
          Input:
          <input ng-model="vm.selected" 
                 ng-value="account"
                 name="selectedAccount"
                 ng-click="vm.resetOthers(account)"
                 type="radio">
        </td>
      </tr>
    </tbody>
  </table>
</div>

AngularJS application

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  let vm = this;

  vm.selected = null;

  vm.items = [{
    rowIsSelected: false
  }, {
    rowIsSelected: false
  }, {
    rowIsSelected: false
  }];
});

> demo fiddle

lin
  • 17,956
  • 4
  • 59
  • 83
0

If you want to radio button get checked, you should set ng-value as true, you can't bind entire complex object it should be boolean.

<input
    ng-value="account.rowIsSelected"
    name="selectedAccount"
    ng-change="vm.selectAccount(account)"
    type="radio">
lucky
  • 12,734
  • 4
  • 24
  • 46
  • This is not correct. `ng-value` accepts mixed types. The documentation says it only allows `string` but this is simply not true. It does allow mixed types. https://docs.angularjs.org/api/ng/input/input%5Bradio%5D. -> AngularJS expression to which ngModel will be be set when the radio is selected. Should be used instead of the value attribute if you need a non-string ngModel (boolean, array, ...). – lin Mar 14 '18 at 11:29