2016-03-16 35 views
6

使用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屬性;

回答

3

瀏覽器只允許li元素在ul元素內。 <ul><menu-item></menu-item></ul><ul><div></div></ul>是無效標記的方式無效。

考慮製作一個<menu>元素,其模板包含ul及其li元素。

另一件事 - 只有少數標準元素是「自我關閉」 - 例如輸入等。自定義元素必須始終具有結束標記。 壞:<menu-item /> 好:<menu-item></menu-item>

你可能想知道「?爲什麼不能奧裏利亞摸不着頭腦的我」

有效的問題。原因如下:Aurelia沒有實現自定義的html解析器。它使用DOM來解析標準HTML。這與人們習慣的其他框架不同,它爲非標準標記語法實現了自定義分析器。

+0

您對關於結構良好的html的建議很有幫助,並且重點突出。在我的真實世界的應用程序中,我使用無容器屬性或@containerless()修飾器。另外需要一個關閉標籤的自定義元素的需求是很好的知道。我將編輯該問題。 但綁定問題仍然存在。你能說一下嗎? – Arjan

相關問題