使用Aurelia我正在努力與綁定和repeat.for: 假設我在我的viewmodel具有屬性menuItems(一個MenuItem
數組)我我想用一個自定義模板重複的菜單項:在aurelia上綁定自定義元素的正確方法是什麼使用repeat.for
export class App {
menuItems : MenuItem[];
}
export class MenuItem{
label:string;
}
在我的應用程序模板,我用使用自定義元素
<require from="./menu-item"></require>
<ul>
<menu-item repeat.for="item of menuItems"></menu-item>
</ul>
我的自定義模板(菜單item.html):
<template>
<li>${label}</li>
</template>
獲取模板綁定或訪問綁定的MenuItem的正確方法是什麼?
我試過以下內容:${label}
和${item.label}
但這不起作用。我可以在bind(bindingContext)
回調中看到bindingContext有一個屬性'item':bindingContext.item
這是被綁定的MenuItem。
我也試圖在MenuItem類創建可綁定屬性:
export class MenuItem{
@bindable current any;
label:string;
}
及以下轉發:
<menu-item repeat.for="item of menuItems" current.bind="item"></menu-item>
和相應的模板
<template>
<li>${current.label}</li>
</template>
注:見編輯下面的1,以便我在代碼中對這一點進行評論。
這種方法也行不通。
其他的探索包括不使用自定義元素(工作),使用<compose view-model='MenuItem', model.bind='item'/>
,在這個例子中也不起作用,我想可以詳細說明。
工作液,也看到Aurelia repeat.for binding on a custom element :
重複和綁定的模板和視圖模型類的自定義屬性:
<menu-item repeat.for="item of menuItems" current.bind="item" containerless></menu-item>
視圖模型類:
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");
}
}
編輯1 :
我看到t他輸出的模板的html重複爲儘可能多的MenuItems。但是這些項目沒有綁定:<li>
是空的。我希望看到標籤。
編輯2:
在這個崗位我輸入「中的菜單項的項目」,這是不正確的應該是「的菜單項的項目」。但是,這是不是我的掙扎的原因,我是有在這個崗位打錯只
編輯3:
@傑里米 - danyow建議
- HTML應該很好地形成:菜單 - ul中的項目不正確(使用
containerless
屬性有助於刪除菜單項元素) - 自定義元素應始終具有結束標記 我已修改代碼。 我也做了一個plunker:Aurelia repeat.for binding on a custom element
這plunker作品,提供了@bindable
屬性;
您對關於結構良好的html的建議很有幫助,並且重點突出。在我的真實世界的應用程序中,我使用無容器屬性或@containerless()修飾器。另外需要一個關閉標籤的自定義元素的需求是很好的知道。我將編輯該問題。 但綁定問題仍然存在。你能說一下嗎? – Arjan