从淘汰模板中读取多个选择列表值 [英] Read multiple select list values from a Knockout Template
本文介绍了从淘汰模板中读取多个选择列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个小时的淘汰赛经验,我正在尝试修改现有的淘汰赛应用程序.它使用挖空中的模板来呈现选择列表的列表.
I'm have a couple of hours of knockout experience and I'm trying to modify an existing knockout application. It uses a template in knockout to render a list of select lists.
Tmpl文件:
<select data-bind="options: $root.AccountIDDropList, optionsText: 'AccountID', optionsValue: 'AccountID', value: selectedAccountID.AccountID, optionsCaption:'-- Select Account --' "></select>
HTML文件:
<div style='margin-left: 5px;' data-bind="template: { name: 'Bank', foreach: Account }"></div>
呈现此代码时,我会得到一个带有帐号的选择列表列表,但是由于每个列表都被命名为 selectedAccountID.AccountID ,当我尝试从每个列表中获取值时,我只能最后一个.
When this renders I get a list of select lists with account numbers in them but since each one is named selectedAccountID.AccountID, when I try to get the value from each one I only can get the last one.
var AccountModel = function(data){
var self = this;
...
};
var viewModel = function(data) {
var self = this
self.selectedAccountID = ko.observable();
self.sendMe = function(){
alert(ko.toJSON({
this.selectedAccountID(),
}));
};
};
ko.applyBindings(new viewModel());
推荐答案
您的请求有些含糊,但是您对此解决方案有何看法
Your request is somewhat vague, but what do you think of this solution
var AccountModel = function(id, name) {
var self = this;
self.id = id;
self.name = name;
};
ko.applyBindings(() => {
var self = this;
self.accountList = [
new AccountModel(1, 'foo'),
new AccountModel(2, 'bar'),
new AccountModel(3, 'stack'),
new AccountModel(4, 'overflow')
];
self.accountSelectedList = ko.observableArray([]);
self.addAccount = () => self.accountSelectedList.push(ko.observable(self.accountList[0]));
self.removeAccount = (index) => self.accountSelectedList.splice(index, 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/html" id="accountTemplate">
<span data-bind="text: $index()"></span>
<select data-bind="options: accountList, optionsText: 'name', value: account"></select>
<a href="#" data-bind="click: () => { removeAccount($index()); }">x</a><br />
</script>
<p data-bind="template: { name: 'accountTemplate', foreach: accountSelectedList, as: 'account', noChildContext: true }"></p>
<p><input type="button" data-bind="click: addAccount" value="Add account" /></p>
<p data-bind="text: _.map(self.accountSelectedList(), function(r) { return `${r().id}: ${r().name}`; }).join(', ')"></p>
这篇关于从淘汰模板中读取多个选择列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文