can't set ng model on checkbox inside ng-repeat

Viewed 241

I have a row of checkboxes, only one can be checked at a time, and if you click on the checkbox that is checked, its state should flip. So if it is checked and you click it, it should uncheck, and vice versa.

model

this.models = [
  {name: 'blah', defaulted: false},
  {name: 'fdsf', defaulted: false},
  ...
]

template

<input 
  type="checkbox"
  ng-repeat="model in vm.models"
  ng-checked="model.defaulted === true" 
  ng-change="vm.setDefault($index)"
  ng-model="model.defaulted" />

a. this one doesn't work, model isn't updated

http://embed.plnkr.co/O275a9O7y60NuimFYdYi?show=preview

this.setDefault = (j) => this.models = this.models.map((m, i) => {
  return j === i 
    ? Object.assign({}, m, {defaulted: !m.defaulted}) 
    : Object.assign({}, m, {defaulted: false}) 
}) 

b. model updates correctly in this one but you are unable to untoggle a checkbox by clicking on it again (hence the !m.defaulted in example a)

http://embed.plnkr.co/MOBuN06R0hmcnpGu01Z7?show=preview

// this works, but now you can't uncheck a box that is checked
this.setDefault = (j) => this.models = this.models.map((m, i) => {
  return j === i 
    ? Object.assign({}, m, {defaulted: true}) 
    : Object.assign({}, m, {defaulted: false}) 
}) 

Need a solution without using radios

4 Answers
Related