嗨,我正在尝试使用observableArray做一个foreach而且我得到了:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: Nome is not defined;
Bindings value: text: Nome
这是我的HTML:
<table data-bind="foreach: funcionarios">
<tr>
<p>Nome: <span data-bind="text: Nome"></span></p>
<p>Apelido: <span data-bind="text: Apelido"></span></p>
<p>Hobby: <span data-bind="text: Hobby"></span></p>
<p>Função: <span data-bind="text: Funcao"></span></p>
<p>Ramal: <span data-bind="text: Ramal"></span></p>
<p>Email: <span data-bind="text: Email"></span></p>
<p>Celular: <span data-bind="text: Celular"></span></p>
<p>Aniversário: <span data-bind="text: Aniversario"></span></p>
</tr>
</table>
这是我的Js:
var FuncionarioViewModel = function () {
var me = this;
function Funcionario(base, id, nome, apelido, hobby, funcao, ramal, email, celular, aniversario) {
var me = this;
me.Id = id;
me.Nome = ko.observable(nome);
me.Apelido = ko.observable(apelido);
me.Hobby = ko.observable(hobby);
me.Funcao = ko.observable(funcao);
me.Ramal = ko.observable(ramal);
me.Email = ko.observable(email);
me.Celular = ko.observable(celular);
me.Aniversario = ko.observable(aniversario);
};
me.funcionarios = ko.observableArray([]);
me.add = function (id, nome, apelido, hobby, funcao, ramal, email, celular, aniversario) {
me.funcionarios.push(new Funcionario(me, id, nome, apelido, hobby, funcao, ramal, email, celular, aniversario));
};
}
var viewModel = new FuncionarioViewModel();
ko.applyBindings(viewModel);
这是小提琴链接:http://jsfiddle.net/Lrqeb/8/
我不想在该数组中加载包含默认数据的页面。
答案 0 :(得分:1)
编辑:
好的,刚检查了你的jsfiddle。我更新了使用if
绑定来检查数组是否包含任何元素,然后再尝试foreach
来阻止绑定错误:
我用foreach
包裹了以下内容:
<div data-bind="if: funcionarios().length > 0">
EDIT2:
此外,您已将foreach
应用于无效的表格标记。我把它更改为使用tbody标签,这在这里工作正常:http://jsfiddle.net/Lrqeb/10/
更改如下所示:
<div data-bind="text: funcionarios().length"></div>
<div data-bind="if: funcionarios().length > 0">
<table>
<tbody data-bind="foreach: funcionarios">
<tr>
<td>Nome: <span data-bind="text: Nome"></span></td>
<td>Nome: <span data-bind="text: Apelido"></span></td>
<!-- and so on... -->
</tr>
</tbody>
</table>