2

The conditionals below arent working with my default template with knockout.js 2.0. It just writes out the IF statements.

  <span data-bind="foreach: admin.home.paging.pages">
        {{if $data == app.viewModel.admin.home.paging.page()}}
        <span data-bind="html: $data"></span>
        {{else}}
        <a href="#" data-bind="click: app.viewModel.admin.home.paging.searchByPage($data), html: $data"></a>
        {{/if}}

    </span>

UPDATE

I did the following instead.

 <span data-bind="foreach: admin.home.paging.pages">
        <span data-bind="html: $root.admin.home.paging.page(), visible: $data == $root.admin.home.paging.page()"></span>
        <a href="#" data-bind="click: function() { $root.admin.home.searchByPage($data); }, html: $data, visible: $data != $root.admin.home.paging.page()"></a>
    </span>

1 Answer 1

8

Your code is using jquery tmpl but by default Knockout uses its native template engine. If you want jquery tmpl, you must override the native engine. If you want the native engine you can use the if binding in the native templates:

<span data-bind="foreach: admin.home.paging.pages">
        <!-- ko if: $data === app.viewModel.admin.home.paging.page() -->
            <span data-bind="html: $data"></span>
        <!-- /ko -->
        <!-- ko if: $data !== app.viewModel.admin.home.paging.page() -->
            <a href="#" data-bind="click: app.viewModel.admin.home.paging.searchByPage($data), html: $data"></a>
        <!-- /ko -->
</span>

However, I recommend a few changes too. I would abstract the logic from your html and make a function in your viewmodel performs the evaluation and returns true/false. For example

<!-- ko if: isSamePage() -->

I would shorten your object hierarchy a bit too, if you can. Also, consider using the with block.

If you are iterating through admin.home.paging.pages, then each object inside of that loop is a child of that object hierarchy. In other words, you don;t have to keep specifying the entire object chain.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.