Using Aurelia, I struggle with binding and repetition. for: suppose I have in my view model with the menuItems property ( MenuItem array). I would like to repeat menu items using a custom template:
export class App { menuItems : MenuItem[]; } export class MenuItem{ label:string; }
In my application template, I use a custom element
<require from="./menu-item"></require> <ul> <menu-item repeat.for="item of menuItems"></menu-item> </ul>
My custom template (menu-item.html):
<template> <li>${label}</li> </template>
What is the correct way to bind a template or access related MenuItem?
I tried the following: ${label} and ${item.label} , but this does not work. In the bind(bindingContext) I see that bindingContext has the property "item": bindingContext.item , which is associated with MenuItem.
I also tried to create a bindable attribute in the MenuItem class:
export class MenuItem{ @bindable current any; label:string; }
and the following repeater:
<menu-item repeat.for="item of menuItems" current.bind="item"></menu-item>
and corresponding template
<template> <li>${current.label}</li> </template>
Note: see edit 1 below for my comment on this point in the code.
This approach also does not work.
Other studies that do not use a custom element (working), using <compose view-model='MenuItem', model.bind='item'/> , do not work in this example and, as I think, will develop.
Working solution, see also Aurelia repeat.for custom element bindings
repeat and bind to the user attribute of the template and viewmodel class:
<menu-item repeat.for="item of menuItems" current.bind="item" containerless></menu-item>
Viewmodel class:
import {bindable, customElement} from 'aurelia-framework' @customElement('menu-item') export class MenuItem{ label = "default label"; @bindable current; constructor(label){ this.label = label; } attached(){ console.log("MenuItem = attached"); } }
Change 1:
I see the output of html templates that are repeated for many, there are MenuItems. But these elements are not related: <li> empty. I expected to see tags.
Edit 2:
in this post I typed "items in menuItems" that the untruth should be "item of menuItems". But this was not the reason for my struggle, I printed it incorrectly only in this post
Edit 3:
@ jeremy-danyow suggested that
- html should be well-formed: the menu item inside ul is incorrect (using the
containerless attribute helps by removing the menu item) - Custom elements should always have a closing tag. I adapted the code. I also made a plunker: Aurelia repeat.for binding to a custom element
This plunker works if the @bindable attribute;