What I'm trying to do is create a DOM node, render a template with ko.renderTemplate overwriting the created node and then, in that template both be able to get data from a specific model AND from the viewModel $root.
Ex:
var data = new ModelData();
var domNode = document.createElement("div");
document.body.appendChild(domNode);
ko.renderTemplate('template', data, {}, domNode, 'replaceNode');
And the template could look like:
<script type="text/html" id="template">
<span data-bind="text: DataFromModel"></span>
<ul data-bind="foreach: $root.DataFromViewModelRoot">
</ul>
</script>
In this case, I don't get any data from $root.DataFromViewModelRoot, because it thinks the $root-data is the ModelData (and I understand why, I just don't know how I should do it).
What I'm trying to accomplish with this is that I need to create a modal-window (bootstrap) from a template, and then I want to be able to display different content in that modal depending on what data I "send in to it". I also need to be able to create multiple modals and that's why I need to create a new DOM node.
I have an improved version of https://stackoverflow.com/a/16160300/2630724 to share:
All you need in addition to this is one element for the modal
somewhere on your page and then you open a dialog by writing to the currentModal observable and you close the dialog by nulling it: currentModal(null)
I'm using bootstrap 3.0-rc1 knockout 2.3 in there which allows a computed as template name :)
Thanks @rp-niemeyer for posting this!
This is a little bit different than your specific question, but here is an alternative way to work with a bootstrap modal.
You can use a custom binding that wraps both bootstrap's
modal
and thetemplate
binding.The binding might look like:
Now, you would bind a single modal on your page like:
currentModal
would be an observable that you populate with an object that contains aname
(the template name) anddata
.The way that this works is that if
currentModal
is populated, then the modal is displayed using the current template and data. IfcurrentModal
is null, then the modal is closed.Here is a sample for how this would work: http://jsfiddle.net/rniemeyer/NJtu7/