选择显示与选项相关的内容

时间:2015-04-21 13:59:42

标签: knockout.js

我试图在下拉菜单中显示仅与所选选项相关的内容。

我已经整理了Fiddle

选择一个选项后,我想显示该特定模型的绑定元素。我不知道我哪里出错了。我是否需要使用$root,或者我错过了select API的一部分?

HTML

<div id="defAccount">
<p>
    Account Option :
    <select data-bind="options: accounts,
                   optionsText: 'accountNumber',
                    value: 'Id', 
                    optionsCaption: 'Choose...'"></select>

    <div class="form-horizontal">
        <div data-bind="visible: accounts().length > 0">
            <label data-bind="text: accounts.Id"></label>
            <label data-bind="text: accounts.accountNumber"></label>
            <label data-bind="text: accounts.participantName"></label>
              <div data-bind="visible: accounts().length < 1">
              <label>There are currently no records to show - sucka.</label>
            </div>
        </div>        

    </div>
</p>
</div>

敲除

// Model
function deferredAccount(data) {
          //  var self = this;

            this.Id = ko.observable(data.Id);
            this.accountNumber = ko.observable(data.AccountNumber);
            this.participantName = ko.observable(data.ParticipantName);
        }

//ViewModel
function accountViewModel(){
    var self = this;
    self.accounts = ko.observableArray([]); 

        $.ajax("/echo/json/", {
        data: {
            json: ko.toJSON(account)
        },
        type: "POST",
        dataType: 'json',
        success: function(data) {
                //2 objects here
            var mAccounts = _.map(data, function(item) {
                return new deferredAccount(item);
            });

            console.log(mAccounts);

            self.accounts(mAccounts);
        }
    });  

}

// Copy
var account = [
    {"Id":1,
     "AccountNumber":100011,
     "ParticipantName":"MICKEY MOUSE"
    },
    {"Id":3,
     "AccountNumber":200011,
     "ParticipantName":"MICKEY MOUSE"
    }
];


ko.applyBindings(new accountViewModel(), document.getElementById("defAccount"));

2 个答案:

答案 0 :(得分:1)

您需要将您的选择存储在viewmodel上并将您的表单绑定到实际选择,而不是支持数组:

http://jsfiddle.net/7u7qebr5/9/

HTML:

<select data-bind="options: accounts,
                       optionsText: 'accountNumber',
                        value: selectedAccount, 
                        optionsCaption: 'Choose...'"></select>
... 

<label data-bind="text: selectedAccount().Id"></label>
<label data-bind="text: selectedAccount().accountNumber"></label>
<label data-bind="text: selectedAccount().participantName"></label>

观察到的:

self.selectedAccount = ko.observable();

答案 1 :(得分:0)

您的选择

上有一些缺失的部分

如果你想绑定选择的所有数据应该像这样

<select data-bind="options: accounts,
       optionsText: 'accountNumber', value: selectedOption, 
       optionValue  :$data,
       optionsCaption: 'Choose...'">

此代码将所选数据选中所有数据绑定到selectedOption,或者您只能使用更改 optionValue:&#39; Id&#39; 绑定所选选项的属性, 并且不要忘记定义selectedOption