Nest knockout foreach templates
I'm trying to nest some jQuery templates. I know jQuery has the {{tmp syntax i can use, but that won't work for me as i need to use knockout's foreach template. As you can see below, i've got a div bound to the first script tag. that's my first template, using knockout's foreach syntax to loop through an observable array of messages. inside that template i'm trying to put another div bound to another template that uses knockout's foreach to loop through an array within each member of the 'messages' array. It's not working. i'm getting javascript errors (like "expected identifier"). any idea what i'm doing wrong??
<div data-bind="template: {name: 'contactIMSTemplateContent', foreach:messages}"></div>
<script id="contactIMSTemplate" type="text/html">
<span cla开发者_如何学编程ss="tabTop">${viewModel.contacts()[$data.contact].name()}</span>
</script>
<script id="contactIMSTemplateContent" type="text/html">
<div class="tabContentIM" >
<div data-bind="template: {name:'IMSTemplate', foreach:${viewModel.messages()[$data.contact].ims}}" ></div>
</div>
</script>
<script id="IMSTemplate" type="text/html">
<div class="message"><span class="messageFrom">${viewModel.contacts()[0].name()}</span> ${$data}</div>
</script>
My viewmodel looks like:
var viewModel = {
contacts: ko.observableArray([new contact("Contact Name", "contact status", "busy", "e@t.com", "url")]),
messages: ko.observableArray([{
contact: 0,
ims: new ko.observableArray(["chat"])
}])
};
I don't know exactly what your viewModel looks like, but this line will cause a problem:
<div data-bind="template: {name:'IMSTemplate', foreach:${viewModel.messages()[$data.contact].ims}}" ></div>
Inside the data-bind, you can use the variables directly and don't need to use ${
syntax. Additionally, at the end of the attribute there is a }}
, which will cause the jQuery templates plugin to try to parse it as a tag. If you ever need to put two braces inside a data-bind, then just put a space between them and it will work.
精彩评论