Dan Black
Dan Black

Reputation: 1217

Knockout foreach not matching length

I'm having trouble displaying items from a knockout observable array.

The code below displays a length of 3 (so I know there are elements), yet the foreach does not display any rows.

<label data-bind="text: Data().length"></label>
<table>
    <tbody data-bind="foreach: Data">
        <tr>
            <td >woot</td>
        </tr>
    </tbody>
</table>

The result of

<label data-bind="text:  ko.toJSON(Data)"></label>

is:

 [ { "Description" : null,
    "DeviceId" : "fake1",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake2",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake3",
    "DeviceType" : null,
    "Policy" : null
  }
]

Any advice much appreciated

Upvotes: 0

Views: 234

Answers (2)

Chirag Arvadia
Chirag Arvadia

Reputation: 1200

<label data-bind="text: Data().length"></label>
<table>
    <tbody data-bind="foreach: Data">
        <tr>
          <td data-bind="text: DeviceId"></td>
          <td>woot</td>
        </tr>
    </tbody>
</table>

<label data-bind="text:  ko.toJSON(Data)"></label>  

<script type="text/javascript"> 
    var JSONdata = [ { "Description" : null,
        "DeviceId" : "fake1",
        "DeviceType" : null,
        "Policy" : null
      },
      { "Description" : null,
        "DeviceId" : "fake2",
        "DeviceType" : null,
        "Policy" : null
      },
      { "Description" : null,
        "DeviceId" : "fake3",
        "DeviceType" : null,
        "Policy" : null
      }
    ];

    function ViewModel() {
        var self = this;
        self.Data = ko.observableArray(JSONdata);  
    }

    ko.applyBindings(new ViewModel());

</script>

Upvotes: 2

mg1075
mg1075

Reputation: 18155

Are you showing all your javascript code in your question?
Regardless, here is a simple working example that includes a table cell for displaying the DeviceId;
hope it helps.

http://jsbin.com/UZIDira/2/edit?html,js,output

HTML

<label data-bind="text: Data().length"></label>
<table>
    <tbody data-bind="foreach: Data">
        <tr>
          <td data-bind="text: DeviceId"></td>
          <td>woot</td>
        </tr>
    </tbody>
</table>

<label data-bind="text:  ko.toJSON(Data)"></label> 

Javascript

var myJSON = [ { "Description" : null,
    "DeviceId" : "fake1",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake2",
    "DeviceType" : null,
    "Policy" : null
  },
  { "Description" : null,
    "DeviceId" : "fake3",
    "DeviceType" : null,
    "Policy" : null
  }
];

function ViewModel() {
    var self = this;
    self.Data = ko.observableArray(myJSON);  
}

// Activates knockout.js
ko.applyBindings(new ViewModel());

Upvotes: 1

Related Questions