jQuery: template from string question
Lets say I have a viewmodel like this
var viewModel = {
"Dtos": [{
"Id": 1,
"Number": 100,
"Description": "some description",
"Total": 200},
{
"Id": 2,
"Number": 200,
"Description": "some description",
"Total": 400}]
};
viewModel.EditUrl = "http://someUrl.com?Id=${Id}";
How can I render the EditUrl in a following template so that containing template processes it as a template; in other words how can I convert that string that is in the viewmodel to a template within template.
<script id="rowTemplate" type="text/x-jquery-tmpl">
<tr>
<td><a href="${EditUrl}">Edit</a&开发者_如何学Gogt;</td>
<td>${Id}</td>
</tr>
</script>
Knockout.js takes care of binding this, so Id renders properly.
How about you make viewModel.EditUrl a function like:
viewModel.EditUrl = function(id) { return "http://someUrl.com?Id=" + id; }
Then, your template would look like:
<script id="rowTemplate" type="text/x-jquery-tmpl">
<tr>
<td><a href="${viewModel.EditUrl(Id)}">Edit</a></td>
<td>${Id}</td>
</tr>
</script>
Like: http://jsfiddle.net/rniemeyer/CegbS/
Otherwise, since you are using knockout, you could consider making EditUrl a dependentObservable on each item in your array. Then, you could actually bind to just EditUrl. Pretty much the same as above, just the function would be on each item in the array. Let me know and I could show you an example of that as well.
精彩评论