KnockoutJS if statement inside foreach loop

后端 未结 2 1601
野性不改
野性不改 2020-12-29 22:48

Here I have this code:


    
         

        
相关标签:
2条回答
  • 2020-12-29 22:55

    One option is to do something like:

    <tbody data-bind="foreach: entries">
        <tr>
            <td>
                <!-- ko if: type === 'file' -->
                    <i class="icon-file"></i>
                    <a href="#" data-bind="text: name, click: $parent.showFile"></a>
                <!-- /ko -->
                <!-- ko if: type !== 'file' -->
                    <i class="icon-folder"></i>
                    <a href="#" data-bind="text: name, click: $parent.goToPath"></a>
                <!-- /ko -->
            </td>
        </tr>
    </tbody>
    

    Sample here: http://jsfiddle.net/rniemeyer/9DHHh/

    Otherwise, you can simplify your view by moving some logic into your view model like:

    <tbody data-bind="foreach: entries">
        <tr>
            <td>
                <i data-bind="attr: { 'class': $parent.getClass($data) }"></i>
                <a href="#" data-bind="text: name, click: $parent.getHandler($data)"></a>
            </td>
        </tr>
    </tbody>
    

    Then, add methods on your view model to return the appropriate value:

    var ViewModel = function() {
        var self = this;
        this.entries = [
            { name: "one", type: 'file' },
            { name: "two", type: 'folder' },
            { name: "three", type: 'file'}
        ];
    
        this.getHandler = function(entry) {
            console.log(entry);
            return entry.type === 'file' ? self.showFile : self.goToPath;
        };
    
        this.getClass = function(entry) {
            return entry.type === 'file' ? 'icon-file' : 'icon-filder'; 
        };
    
        this.showFile = function(file) {
            alert("show file: " + file.name);
        };
    
        this.goToPath = function(path) {
            alert("go to path: " + path.name);
        };
    };
    

    Sample here: http://jsfiddle.net/rniemeyer/9DHHh/1/

    0 讨论(0)
  • 2020-12-29 23:00

    You can use the containerless control flow syntax, which is based on comment tags:

    <tbody data-bind="foreach: entries">
        <tr>
            <!-- ko if: type === "file" -->
                <td><i class="icon-file"></i> <a href="#" data-bind="text: name, click: $parent.showFile"></a></td>
            <!-- /ko -->
            <!-- ko if: type !== "file" -->
                <td><i class="icon-folder"></i> <a href="#" data-bind="text: name, click: $parent.goToPath"></a></td>
            <!-- /ko -->
        </tr>
    </tbody>
    
    0 讨论(0)
提交回复
热议问题