动态取自可观察数组项属性值的挖空模板名称
knockout template name dynamically taken from observable array item property value
我是“knockout”的新手,请耐心等待。
我有一个由对象组成的可观察数组,其中一个属性(“模板类型”)包含要使用的模板的名称。如何在 HTML 中迭代可观察数组时动态分配属性值(模板类型)?
//Short version of an array object (‘containerData’ is read from MVC)
function smContainerViewModel(containerData) {
var self = this;
self.id = ko.observable(containerData.id);
self.templateType = ko.observable(containerData.containerType);
};
//viewModel
function AppViewModel(dataInput) {
var self = this;
self.koContainersArray = ko.observableArray();
for (var i = 0; i < dataInput.containersArray.length; i++) {
self.koContainersArray.push(new smContainerViewModel(dataInput.containersArray[i]));
};
self.currentTemplate = ko.computed(function () {
//Currently I can return the below static name of a template. I would like to return:
// koContainersArray()[index]. templateType;
return 'template1';
});
};
var viewModelSM = new AppViewModel(initialData);
ko.applyBindings(viewModelSM);
//HTML
<div data-bind="template:{name:currentTemplate ,foreach:koContainersArray}"></div>
你快到了。
<!-- ko foreach: koContainersArray -->
<div data-bind="template: templateType"></div>
<!-- /ko -->
只要设置为 templateType
的模板 1 或模板的 ID 是什么,这就可以工作。
这是一个例子fiddle -
我是“knockout”的新手,请耐心等待。 我有一个由对象组成的可观察数组,其中一个属性(“模板类型”)包含要使用的模板的名称。如何在 HTML 中迭代可观察数组时动态分配属性值(模板类型)?
//Short version of an array object (‘containerData’ is read from MVC)
function smContainerViewModel(containerData) {
var self = this;
self.id = ko.observable(containerData.id);
self.templateType = ko.observable(containerData.containerType);
};
//viewModel
function AppViewModel(dataInput) {
var self = this;
self.koContainersArray = ko.observableArray();
for (var i = 0; i < dataInput.containersArray.length; i++) {
self.koContainersArray.push(new smContainerViewModel(dataInput.containersArray[i]));
};
self.currentTemplate = ko.computed(function () {
//Currently I can return the below static name of a template. I would like to return:
// koContainersArray()[index]. templateType;
return 'template1';
});
};
var viewModelSM = new AppViewModel(initialData);
ko.applyBindings(viewModelSM);
//HTML
<div data-bind="template:{name:currentTemplate ,foreach:koContainersArray}"></div>
你快到了。
<!-- ko foreach: koContainersArray -->
<div data-bind="template: templateType"></div>
<!-- /ko -->
只要设置为 templateType
的模板 1 或模板的 ID 是什么,这就可以工作。
这是一个例子fiddle -