jimmyco2008 jimmyco2008 - 4 months ago 13
Javascript Question

Knockout "If viewModel property contains 'some text'"

I was relying on the answer here How to check contain in knockout but it seems to be for an outdated version of Knockout. I'm trying to do something like:

<li>
<span data-bind="text: Subject"></span>
<!-- ko if: Subject.contains('Important') -->
<i class="fa fa-exclamation-triangle"></i>
<!-- /ko -->
</li>


Where the fontawesome icon is appended to the ko Subject text if that Subject text contains the word 'Important'. This however does not work ('contains' is not a function), and I am struggling to find an "up-to-date" solution.

Answer

This is what I ended up with:

<li>
   <span data-bind="text: Subject"></span>
   <!-- ko if: Subject().indexOf('Important') !== -1 -->
   <i class="fa fa-exclamation-triangle"></i>
   <!-- /ko -->
</li>

And it works! Thanks, Matt.kaaj. I think Roy's way is the way to go if this is something I'm doing in multiple places, but since I'm only checking the string for a keyword once in the site, I went with the straightforward inline solution. Thank you both!