1
function MyViewModel() {
  var self = this;
  this.addPerson = function () {
    this.PersonIdList.push(0);
  }

  this.showSecondSection = ko.computed(function() {
    // need logic here?
  }, this);

  this.PersonIdList = ko.observableArray();
  this.PeopleChoices = ko.observableArray([
    {
      "Id": 1,
      "Name": "Person A"
    },
    {
      "Id": 2,
      "Name": "Person B"
    },
    {
      "Id": 3,
      "Name": "Person C"
    },
  );
}


<!-- ko foreach: PersonIdList -->
<div class="container" style="margin-bottom: 5px;">                
  <select id="idList" data-bind="options: $root.PeopleChoices, optionsValue: 'Id', optionsText: 'Name', optionsCaption: '-- Please Select --', value: ??"></select>                                                             
</div> 
<div data-bind="visible: showSecondSection">Hi</div>
<!-- /ko -->
<a href="javascript:void(0);" data-bind="click: addPerson">Add person</a>

我想知道是否可以将此块数据绑定到 PersonIdList 中的项目?另外,如果 Id = 3,我可以在循环内创建一个有条件可见的第二个 div 容器吗?

4

2 回答 2

2

如果我对您的理解正确,您将拥有一个绑定到 foreach 的 observableArray 的 ID。在每个<div>s 中,您都有一个绑定到 PeopleChoices 数组的选择选项列表(下拉列表)。并且您想将 PersonID 的当前迭代绑定到下拉列表的值?

我不确定您想要的结果是什么,或者您为什么要这样做。这是可能的,有点。我不确定在下拉列表中选择新选项时会发生什么。我猜什么都不会发生,什么也没有发生。这是小提琴

您所要做的就是将值绑定设置为$data如下所示:

<select id="idList" data-bind="options: $root.PeopleChoices, optionsValue: 'Id', optionsText: 'Name', optionsCaption: '-- Please Select --', value: $data"></select>

在 personIdList 的每次迭代中,$data 都会设置选定的值,但是一旦更改了选择,就不会发生任何事情,因为 observableArray 中填充了静态数据。所以我想,如果它们是可观察的呢?所以我更新了小提琴,虽然它至少会更新 observable 中的值,但它没有。

所以,是的,你可以,但这很奇怪。不知道你为什么要这样做。

更新:可以做这样的事情

于 2013-09-08T01:16:25.940 回答
1

http://jsfiddle.net/4Dv3y/1/

看看这个亚当。我认为这是一个更清洁的解决方案,并且您正在使用可观察对象,并且您还可以使用诸如 showValue 之类的属性来在需要时显示跨度。这更多的是你应该如何在 Knockout 中使用 observables,当你在 JavaScript 中使用像这样的强大对象时,你不想依赖索引。

<div data-bind="with: selectedPerson">
The name of the person that is selected is : <span data-bind="text: Name"></span>
<h4 data-bind="visible: ShowHighlight">OMG SECOND PERSON IS SHOWN!</h4>
</div>
于 2013-09-08T13:57:28.310 回答