问题
I was following a video about knockout and I have no idea why my code is not working.
I'm using these js scripts:
<script src="assets/js/knockout-2.0.0.js" type="text/javascript"></script>
<script src="assets/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.tmpl.min.js" type="text/javascript"></script>
<h2>Friends</h2>
<ul data-bind="template: {name: 'friendsTemplate', foreach:friends}"></ul>
<script type="text/html" id="friendsTemplate">
<li>${ data.name }</li>
</script>
<script type="text/javascript">
function friend(name) {
return { name : ko.observable(name) };
}
var viewModel = {
friends : ko.observableArray([new friend('João'), new friend('Lucas')])
};
ko.applyBindings(viewModel);
</script>
This code returns me this, it is showing the correct amount of friends but not displaying the names.
Friends
${ data.name }
${ data.name }
What am I doing wrong?
Thanks in advance.
EDIT Making some tests and this code works because it is not using template, so my code is correct, the problem is only with template.
<script type="text/html" id="friendsTemplate">
<li><span data-bind="text: name"></span></li>
</script>
回答1:
you should reference jquery.tmpl prior to knockoutjs
<script src="assets/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.tmpl.min.js" type="text/javascript"></script>
<script src="assets/js/knockout-2.0.0.js" type="text/javascript"></script>
and change ${ data.name } to ${name}
http://jsfiddle.net/c8Svk/
回答2:
Try:
<script type="text/html" id="friendsTemplate">
<li>$data.name</li>
</script>
Alternatively, you could just do:
<script type="text/html" id="friendsTemplate">
<li data-bind="text: name"></li>
</script>
来源:https://stackoverflow.com/questions/9277588/knockoutjs-template-not-working