Reputation: 871
I went through the knockout tutorial of binding data to a template using foreach and I got that to work. I can make a successful ajax call to a controller and I see that the data is the same as the hardcoded data. But I get nothing on the screen. No errors in the javascript console.
My assumption is that I need to change the syntax around a little. I've googled for a few hours but cannot find a good example. Does anyone have a good example that uses an ajax call to populate a knockout template?
Here is my js code:
function RecordViewModel(url) {
var self = this;
self.cards = ko.observableArray();
self.loadData = function () {
$.get(url.load, function (data) {
self.cards = data;
});
}
}
var vm = new RecordViewModel({
load: '/records/getcards'
});
$(function () {
vm.loadData();
ko.applyBindings(vm);
});
The html:
<script type="text/html" id="record-template">
<table>
<tr>
<td><span data-bind="text:artist" /></td>
</tr>
<tr>
<td><span data-bind="text:description" /></td>
</tr>
<tr>
<td rowspan="3"><span data-bind="text:price"></span></td>
</tr>
</table>
</script>
<div data-bind="template: {name: 'record-template', foreach: cards() }"></div>
Upvotes: 1
Views: 300
Reputation: 17906
As far as i know you rather set the value of an observable like this:
self.cards(data)
instead of
self.cards = data;
Upvotes: 3