Knockout.js using open tags in an if statement

I have the following code ...

<div data-bind="foreach:profiles">
    <!-- ko if: $index() % 3 === 3 -->
            <div class="form-group">
    <!-- /ko -->
            <div class="col-xs-3 col-md-1 no-padding-left">
                  <img class="img-circle text-center" src="\Content\images\fake_profile_pics\md.png" alt=".." style="opacity: 1.9" />
                  <h5 class="text-center"><span data-bind="text:Points"></span><span> points</span></h5>
            </div>
            <div class="col-xs-9 col-md-3">
                  <a href="#" class="profile_popover people-h2" data-bind="text:DisplayName"></a>
                  <span class="display-block" data-bind="text:Division"></span>
                  <span class="display-block"><span data-bind="text:NominationsWritten"></span><span> Nominations Written</span></span>
            </div>
     <!-- ko if: $index() % 3 === 1 -->
            </div>
     <!-- /ko -->
</div>

I am trying to create a series of objects, 3 objects wide, and they all start with the height of the lowest element of the line above it. The problem with this code is that the knockout cannot find the end tag for the first div and breaks without errors. If you put the end tag in the first ko if statement, everything works fine.

Can this be used using the knockout comment method, or is there a more acceptable way to solve this knockout problem?

+4
source share
2 answers

, , computed , . , :

function ViewModel() {
    var self = this;
    self.someStuff = ko.observableArray();
    //... other props
}

, :

function ViewModel() {
    var self = this;
    var numCols = 3;
    self.someStuff = ko.observableArray();

    self.columns = ko.computed(function () {
        var source = self.someStuff();
        if (source && source.length) {
            var cols = [];
            for (var i=0; i < source.length; i+=numCols) {
                cols.push(source.slice(i,numCols));
            }
            return cols;
        }
    });
    //... other props
}

. , .

:

<div data-bind="foreach:columns">
    <div class="form-group" data-bind="foreach:$data>
        <div>
            <!-- bind whatever properties you want here -->
        </div>
    </div>
</div>

. , .

+2

if div class?

<div data-bind="css: { 'form-group': $index() % 3 === 3 }">
    ...
</div>
+2

Source: https://habr.com/ru/post/1537552/


All Articles