【问题标题】:Knockoutjs template foreach, special first itemKnockoutjs 模板 foreach,特殊第一项
【发布时间】:2013-03-11 13:42:55
【问题描述】:

所以我一直在绞尽脑汁想办法解决这个问题。我有一个 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 验证。

【问题讨论】:

    标签: knockout.js jquery-validate


    【解决方案1】:

    查看我对 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>
    

    【讨论】:

    • 谢谢,成功了!我仍然在验证方面遇到了一些问题,但至少我现在可以拥有一个特殊的第一项。
    • 好的,现在也解决了。再次非常感谢:)
    • 令人难以置信的是,尝试在数据绑定中的实际“if”中使用相同的东西是行不通的(我正在打开迭代变量,所以我的用例有点不同...)
    【解决方案2】:

    您应该能够使用计算的 observable 来返回布尔值,如果布尔值为真,则显示属性(标准淘汰赛)?

    可能是这样的

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

    它看起来很老套,但应该可以工作

    或使用

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

    【讨论】:

    • 也感谢您的贡献:) 我已经找到了合适的答案,但我会保存它以供将来参考。
    【解决方案3】:

    我很想使用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);
        }
    };
    

    【讨论】:

    • 感谢您的贡献 :) 我已经找到了合适的答案,但我会保存它以供将来参考。
    【解决方案4】:

    只要您从索引中删除括号,早期的帖子就可以使用。

    喜欢下面的

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      相关资源
      最近更新 更多