Knockoutjs template foreach, special first item

2019-04-19 08:42发布

So i have been busting my brain figuring this out. I have a foreach, spitting out templates, and i want the first element to have a special attribute. So far solutions i have found havent worked.

This is the foreach:

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

This is the template:

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

And i want to add: "validate="required:true, minlength:2" to the first element.

What do i need to do?

If it helps, its for jQuery validation.

3条回答
Viruses.
2楼-- · 2019-04-19 08:53

I'd be tempted to use custom binding rather than a template, and then get the $index off the bindingContext, and add the validate attribute only when $index is 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);
    }
};
查看更多
狗以群分
3楼-- · 2019-04-19 08:57

You should be able to use a computed observable to return a boolean and if the boolean is true you show the attribute(standard knockout)?

something like this maybe

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

it seems hacky but should work

or use

   {{if $item.first === $data}}
查看更多
霸刀☆藐视天下
4楼-- · 2019-04-19 09:10

check my answer for another question about the first element in 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>
查看更多
登录 后发表回答