0
// Model
function User(item) {
  var self = this;
  this.id = ko.observable(item.id);
  this.name = ko.observable(item.name);
  this.surname = ko.observable(item.surname);
  this.email = ko.observable(item.email);
  // item.enabled is a boolean value.
  this.enabled = ko.observable(item.enabled);
  this.credit = ko.observable(new Credit(item.credit));
  this.roles = ko.observableArray(item.roles);
}    

<div data-bind='foreach: users'>
  <!-- This below prints 1 -->
  <span class='badge ' data-bind='text: enabled' ></span>

  <!-- Both of those below don't activate (if check fails) -->
  <span class='badge badge-success' data-bind='if: enabled==1'>OK</span>
  <span class='badge ' data-bind='if: enabled==0' >NO</span>
</div>

我试过了:

<span class='badge badge-success' data-bind='if: enabled==1'>OK</span>
<span class='badge badge-success' data-bind='if: enabled'>OK</span>
<span class='badge badge-success' data-bind='if: enabled()'>OK</span>
<span class='badge badge-success' data-bind='if: enabled=="1"'>OK</span>

没有运气。我究竟做错了什么?

4

1 回答 1

1

你很接近,但正确的语法是

<span class='badge badge-success' data-bind='if: enabled() == 1'>OK</span>
<span class='badge ' data-bind='if: enabled() == 0' >NO</span>

演示JSFiddle

因为enabled它是一个可观察对象(它是一个函数),所以您需要通过不带任何参数调用它来获取它的值:enabled()当您在表达式中使用它时。

于 2013-10-23T18:45:45.500 回答