您可以将模板与隐藏元素的单独模型一起使用:
HTML
<div data-bind="template: { name: 'hidden-template', data: first }"></div>
<div data-bind="template: { name: 'hidden-template', data: second }"></div>
<script type="text/html" id="hidden-template">
<a data-bind="click: showHidden, visible: isVisible, text : linkText" href="#"></a>
<div data-bind="visible: !isVisible(), html: content" style="display:none"></div>
</script>
JS
var hiddenModel = function(linkText, content) {
this.linkText = linkText;
this.content = content;
this.isVisible = ko.observable(true);
this.showHidden = function(){
this.isVisible(false)
};
}
var vm = function() {
this.first = new hiddenModel('Show first', 'hidden content first');
this.second = new hiddenModel('Show second', 'hidden content second');
};
注意:对于这两个元素,这可能开销太大,但只要您需要更多隐藏物品,它就会得到回报。任何额外的元素都只需要一行简短的 HTML 和 JS。
具有绑定的复杂模板的更新:
如果您的 HTML 内容本身包含绑定,您也可以将其放入模板中并动态加载它们
工作示例
HTML
<div data-bind="template: { name: 'hidden-template', data: first }"></div>
<script type="text/html" id="content-first">
test simple content
</script>
<div data-bind="template: { name: 'hidden-template', data: second }"></div>
<script type="text/html" id="content-second">
test content <a href="#" data-bind="click:testBtn">with binding</a>
</script>
<script type="text/html" id="hidden-template">
<a data-bind="click: showHidden, visible: isVisible, text : linkText" href="#"></a>
<div data-bind="visible: !isVisible(), template: { name: content, data: $parent }" style="display:none"></div>
</script>
JS
var hiddenModel = function(linkText, content) {
this.linkText = linkText;
this.content = content;
this.isVisible = ko.observable(true);
this.showHidden = function(){
this.isVisible(false)
};
}
var vm = function() {
this.testBtn = function(){alert('it works');}
this.first = new hiddenModel('Show first', 'content-first');
this.second = new hiddenModel('Show second', 'content-second');
};
content
现在是模板 id 而不是 HTML 字符串。