CheckBox and View-Model

The documentation says that there is two-way binding with check boxes. To me, this implies that if the model changes the UI would change. However, if I change the “selected_items” on the model, the view doesn’t change.

the check box looks something like this:

<input type="checkbox" checked.bind="selected_items" model.bind="{item_id: 1}"/>
<input type="checkbox" checked.bind="selected_items" model.bind="{item_id: 2}"/>

if, from the model, I push “{item_id: 1}” to selected_items, I would expect the checkbox to appear checked. (selected_items is an array of items).

Is this way it is supposed to work? if not, how can I reflect changes to the model in the view?

1 Like

In the html, literal object are created and assign to model of the checkboxes, which by default will make Aurelia unable to compare the value, since the object created in the view model will be different with the object created in the view. Simply this:

{ item_id: 1 } !== { item_id: 1}

What you can do is to give each checkbox a matcher, as an equality instruction so it can handle the above scenario:

    <input type="checkbox"
      checked.bind="selected_items"
      model.bind="{item_id: 1}"
      matcher.bind="itemMatcher" />

You can have more read on this at Binding: Checkboxes | Aurelia

A demo for this is at https://discourse.aurelia.io/t/checkbox-and-view-model/2487 - CodeSandbox

2 Likes