简体   繁体   English

如果块被淘汰,则无法观察到数组长度

[英]Knockout not observable array length inside if block

I have one 'not observable' array of objects in view-model and I want to render some div-s according to the array. 我在视图模型中有一个对象的“不可观察”数组,我想根据该数组渲染一些div。

<div data-bind="foreach: sequences">
    <!-- ko if: $parent.sequences.length-1 > $index -->
        <div>Some content </div>
    <!-- /ko -->        
</div>

Code above should render div for all elements except the last one, but it does not work, I did not get any error, I do know what is happening ? 上面的代码应该为除最后一个元素之外的所有元素呈现div,但是它不起作用,我没有收到任何错误,我知道发生了什么?

$index is an observable, so you need to use $index() : $index是可观察的,因此您需要使用$index()

<div data-bind="foreach: sequences">
    <!-- ko if: $parent.sequences.length-1 > $index() -->
        <div>Some content </div>
        <div data-bind="text: $data"></div>
    <!-- /ko -->        
</div>

Demo JSFiddle . 演示JSFiddle

You can use the visible binding for this: 您可以为此使用可见绑定:

<div data-bind="foreach: sequences">
    <div data-bind="visible: $parent.sequences.length-1 >  $index()">
      Some content 
    </div>   
 </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM