How to check contain in knockout

六月ゝ 毕业季﹏ 提交于 2019-12-14 01:38:31

问题


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



来源:https://stackoverflow.com/questions/22876740/how-to-check-contain-in-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!