2016-05-03 72 views
1

我有HTMLBars模板,它具有標籤和Ember輸入組件,我想知道什麼是最好的方式來設置標籤引用組件的屬性。有沒有辦法從組件外部訪問組件ID?我知道你可以在組件上手動設置ID但是我想避免這樣做,以防萬一這會導致重複的ID衝突Ember.js設置標籤上的屬性

回答

1

我親自將input上的ID手動設置爲輸入字段和當前組件ID。

所以在我my-form.hbs我這樣做:

<label for=(concat elementId '-username')>Username</label> 
{{input id=(concat elementId '-username') value=username}} 

<label for=(concat elementId '-password')>Username</label> 
{{input id=(concat elementId '-password') value=username}} 

這是簡單而有效的。它將保證uniq id,因爲elementId是uniq。也許你還可以寫一個組件來包裝這個:

輸入與標籤/ component.js

export default Ember.Component.extend({ 
    tagName: '', 
    inputId: Ember.computed({ 
    get() { 
     return Ember.guidFor(this)+'-inpudid'; 
    } 
    }) 
}); 

輸入與標籤/ template.hbs

<label for=inputId>{{label}}</label> 
{{input id=inputId value=value placeholder=label}} 

然後使用它:

{{input-with-label value=username label="Username"}} 
{{input-with-label value=password label="Password"}} 
+0

你知道嗎?這裏解決方案的任何副作用? – ykaragol

+0

有沒有辦法從路線上的模板獲取唯一的ID,而是將所有內容都放在組件中? – jpoiri

+0

@jpoiri您可以在初始化器中重新打開'Ember.Controller',並在您調用'Ember.guidFor(this)'的地方添加一個'uniqId'屬性。 @ykaragol我不認爲有任何。 – Lux

相關問題