1

嗨,我正在尝试使用 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/

我不想使用该数组中的默认数据加载页面。

4

1 回答 1

1

编辑:

好的,刚刚检查了你的jsfiddle。我更新为使用if绑定来检查数组是否包含任何元素,然后再尝试foreach将停止绑定错误:

http://jsfiddle.net/Lrqeb/6/

我用foreach以下内容包裹了你:

<div data-bind="if: funcionarios().length > 0">

编辑2:

此外,您已将 应用于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>

于 2012-08-06T19:02:51.997 回答