Knockoutjs模板foreach,特别第一项

时间:2013-03-11 13:42:55

标签: knockout.js jquery-validate

所以我一直在破坏我的大脑。我有一个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>

我想添加:“validate =”required:true,minlength:2“到第一个元素。

我需要做什么?

如果有帮助,那就是jQuery验证。

4 个答案:

答案 0 :(得分:31)

检查我的答案,了解有关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>

答案 1 :(得分:0)

您应该能够使用计算的observable返回布尔值,如果布尔值为true,则显示属性(标准敲除)?

这样的事可能

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

看起来很hacky但应该工作

或使用

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

答案 2 :(得分:0)

我很想使用custom binding而不是模板,然后从bindingContext获取$ index,并仅在$ index为0时添加validate属性。

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);
    }
};

答案 3 :(得分:0)

只要您删除索引的括号,以前的帖子就可以工作。

喜欢以下内容

<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>

相关问题