How to check contain in knockout

2019-07-17 18:08发布

问题:

I am using knockout and i have one html page where i want to check string with some value. Like i have one string 'A:B:C:D:F:G:H:I', i just want to check this string in html with knockout if. Model

 var viewModel = function () {
   var self = this;
   self.key = ko.observable("A:B:C:D:F:G:H:I");
 }

View

<!-- ko if: key().contains('A') -->
    <input type="checkbox" checked="checked" value="A"/>
 <!-- /ko -->
  <!-- ko if: key().contains('B') -->
    <input type="checkbox" checked="checked" value="B"/>
 <!-- /ko -->

In this lets say key is a string , i want to check if key contain A then do some, if B then do some other thing. How to achieve it with knockout.

回答1:

I just saw this question. Even I was stuck with same problem. I have found a solution, It may help someone.

 var viewModel = function () {
   var self = this;
   self.key = ko.observable("A:B:C:D:F:G:H:I");
 }

So in your view you can do something like this

<!-- ko if: key().indexOf('A') > -1 -->
    <input type="checkbox" checked="checked" value="A"/>
<!-- /ko -->
<!-- ko if: key().indexOf('B') > -1 -->
    <input type="checkbox" checked="checked" value="B"/>
<!-- /ko -->


回答2:

There are two way to check.first is you can directly check whether key contain A or not in binding like this:-

  <!-- ko if: key().contains('A') -->
    <input type="checkbox" checked="checked" />
  <!-- /ko -->

but i think this is not the better way so instead of this you can use ko.computed to check.

 var viewModel = function () {
   var self = this;
   self.key = ko.observable("this A is test");
   self.keyCheck = ko.computed(function () {
      var key = self.key();
      return key && key.contains('A') ? true : false
   });
 }

view:-

  <!-- ko if: keyCheck -->
      Contains A:<input type="checkbox" checked="checked" />
  <!-- /ko -->
  <!-- ko ifnot: keyCheck -->
      Not Contains A:<input type="checkbox" value="ASM" />
  <!-- /ko -->

Fiddle Demo