Binding a select to an array of objects in Aurelia and matching on ID

隐身守侯 提交于 2019-12-03 12:25:30

Specify a matcher function (equality comparer):

<select value.bind="group.users[0]" matcher.bind="userComparer">
  <option repeat.for="user of userService.users" model.bind="user">
    ${user.firstName} ${user.lastName}
  </option>
</select>
export class Foo {
  ...
  userComparer = (userA, userB) => userA.id === userB.id;
  ...
}

Below is the original answer (before 11/30/2015 release)...

Until this is supported natively by aurelia's select binding I would try something like this:

<select value.bind="group.users[0] | userToId:userService.users">
  <option repeat.for="user of userService.users" model.bind="user.id">
    ${user.firstName} ${user.lastName}
  </option>
</select>
export class UserToIdValueConverter {
  toView(user, users) {
    return user ? user.id : null;
  }

  fromView(id, users) {
    return users.find(u => u.id === id);
  }
}

Here's a plunker: http://plnkr.co/edit/15XHkQ?p=preview

You'll probably want to make the converter generic so you can reuse it throughout your app... maybe something like this:

export class ToIdValueConverter {
  toView(obj, idPropertyName, objs) {
    return obj ? obj[idPropertyName] : null;
  }

  fromView(id, idPropertyName, objs) {
    return objs.find(o => o[idPropertyName] === id);
  }
}
<select value.bind="group.users[0] | toId:'id':userService.users">
  <option repeat.for="user of userService.users" model.bind="user.id">
    ${user.firstName} ${user.lastName}
  </option>
</select>

Keep an eye on this issue for updates on native framework support for this scenario.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!