2013-03-11 57 views
13

所以我一直在破解我的腦子搞清楚這一點。我有一個foreach,吐出模板,我想要第一個元素有一個特殊的屬性。到目前爲止我找到的解決方案還沒有成功。Knockoutjs模板foreach,特別第一項

這是在foreach:

<h3 class="question">Geografi</h3> 
     <p class="answer" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }"></p> 

這是模板:

<script id="geographyTmpl" type="text/html"> 
<input class="geoCheckList" validate="required:true, minlength:2" name="geoCheckList[]" type="checkbox" data-bind='value: $data, attr: { id: "Geo"+$index()},checked: $root.selectedGeographies' /> 
<label data-bind="text: $data, attr: { 'for': 'Geo'+$index()}"></label> 

,我想補充說: 「驗證=」 要求:真實,使用MINLENGTH:2"到第一個元素

我需要做什麼?

如果有幫助,它的jQuery驗證。

回答

30

檢查我的答案另一個問題有關的第一個元素在KnockoutJS foreach

Skip item in foreach knockout js array?

<div data-bind="text: ItemsArray[0].someProperty"></div> 
<div data-bind="foreach: ItemsArray"> 
<!-- ko if: $index() == 0 --> 
    <div data-bind="text: someProperty"></div> 
<!-- /ko --> 
<!-- ko if: $index() != 0 --> 
    <div data-bind="text: anotherDifferentProperty"></div>  
<!-- /ko --> 
</div> 
+0

謝謝,這工作!我仍然在驗證方面遇到了一些麻煩,但至少我現在可以有一個特殊的第一項。 – 2013-03-11 14:14:29

+0

好了,現在就修好了。再次感謝:) – 2013-03-11 14:26:28

+0

你歡迎.... – 2013-03-11 14:34:13

0

你應該能夠使用計算的observable返回一個布爾值,如果布爾值爲true,你顯示的屬性(標準淘汰賽)?

這樣的事情也許

this.IsFirst = ko.computed(function() { 
    return this == Array[0]; 
}, this); 

似乎哈克,但應該工作

或使用

{{if $item.first === $data}} 
+0

也感謝您的貢獻:)我已經找到了合適的答案,但我會保存此備查。 – 2013-03-11 14:28:30

0

我會嘗試使用custom binding,而不是一個模板,然後得到綁定上下文的$ index,並且僅當$ index爲0時才添加驗證屬性。

ko.bindingHandlers.yourBindingName = { 
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     // Create your input and label elements here then 
     $(element).append(// add your new elements in here); 
    } 
}; 
+0

謝謝你的貢獻:)我已經找到了合適的答案,但我會保存這個以備將來參考。 – 2013-03-11 14:27:11