Knockoutjs模板的foreach,特殊的第一项(Knockoutjs template fo

2019-08-17 11:37发布

所以我一直在破坏我的大脑搞清楚了这一点。 我有一个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验证。

Answer 1:

检查我的回答有关KnockoutJS的第一个元素的另一个问题foreach

跳过的foreach淘汰赛JS数组项?

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


Answer 2:

您应该能够使用计算出的可观测到返回一个布尔值,如果布尔是真实的告诉你的属性(标准淘汰赛)?

这样的事情也许

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

似乎哈克,但应该工作

或使用

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


Answer 3:

我会尝试使用自定义绑定 ,而不是一个模板,然后拿到$指数掉的BindingContext,并添加验证属性,只有当$指数为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);
    }
};


文章来源: Knockoutjs template foreach, special first item