You can use the template along with a separate model for hidden elements:
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'); };
Note. For these two elements, this may be too much overhead, but as soon as you need more hidden elements, it pays off. Any additional element needs only one short line of HTML and JS.
UPDATE FOR INTEGRATED DETECTION TEMPLATE:
If your HTML content contains the bindings themselves, you can put it in templates and load them dynamically
Working example
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 now a template identifier instead of an HTML string
Fabian schmengler
source share