knockoutjs template not working

帅比萌擦擦* 提交于 2019-12-11 04:48:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!