2013-04-04 73 views
1

我有以下工作車把代碼的前兩個條目:遍歷的枚舉

{{#each phoneNumber in switchboardEntry.sipAccount.phoneNumbers}} 
    <span class="label"> 
    {{phoneNumber.number}} 
    </span> 
{{/each}} 

但我想循環剛的switchboardEntry.sipAccount.phoneNumbers前兩個項目,而不是通過配套。我在http://emberjs.com/guides/enumerables/上找到了一個過濾器示例,但仍然處於Ruby思維模式下,我試圖在switchboardEntry.sipAccount.phoneNumbers之後放置該過濾器,但這不起作用。

解決此問題的最佳方法是什麼?

+0

你就不能使用'switchboardEntry.sipAccount.phoneNumbers [0]'和'switchboardEntry.sipAccount.phoneNumbers [1]'在這種情況下? – 2013-04-04 09:21:25

+0

@FinnMacCool這樣做並不那麼靈活,如果他稍後想要列表中的3或4個項目。也重複的代碼:) – mbogh 2013-04-04 09:29:08

+0

是啊,如果他打算稍後改變它,你的解決方案肯定會更好。 – 2013-04-04 09:32:36

回答

2

您可以將計算屬性添加到sipAccount模型。

事情是這樣的,也許:

App.SipAccount = DS.Model.extend({ 
    phoneNumbers: DS.hasMany('App.PhoneNumbers'), 

    phoneNumberShortList: Ember.computed(function() { 
     var phoneNumbers = this.get('phoneNumbers'); 
     return phoneNumbers.slice(0,2); 
    }).property('[email protected]') 
}); 

更新

車把代碼將被:

{{#each phoneNumber in switchboardEntry.sipAccount.phoneNumberShortList}} 
    <span class="label"> 
    {{phoneNumber.number}} 
    </span> 
{{/each}} 
+0

'property('phoneNumbers。@ each.number')'是什麼?這只是一個名字嗎? – wintermeyer 2013-04-04 10:26:34

+0

它告訴Ember獲取每個電話號碼的號碼屬性。 如果您只是寫了屬性('phoneNumbers'),那麼您的Handlerbars模板{{phoneNumber.number}}的呈現將解析爲undefined。只有屬性ID存在。 如果您還需要顯示例如它應該是屬性標籤:property('phoneNumbers。@ each.number','phoneNumbers。@ each.label') – mbogh 2013-04-04 11:02:12

0
<span class="label"> 
    {{switchboardEntry.sipAccount.phoneNumbers.0.number}} 
</span> 

<span class="label"> 
    {{switchboardEntry.sipAccount.phoneNumbers.1.number}} 
</span> 

OR

{{#with switchboardEntry.sipAccount.phoneNumbers}} 
    <span class="label"> 
    {{0.number}} 
    </span> 

    <span class="label"> 
    {{1.number}} 
    </span> 
{{/with}} 

Fiddle