I have a need to bind some HTML to an object, but my issue is that I don't know the properties of the object at development time.
I have a selectedItem
property in my main view model which I have bound to a section in my HTML:
<div data-bind="with: selectedItem">
</div>
Now I want to generate a table based on the property name and property values:
<div data-bind="foreach: [WHAT DO I PUT HERE?]">
<label class="control-label"><span data-bind="text: [OR HERE?]" /></label>
</div>
I have really no idea how to do this. Any help is greatly appreciated.
Also, just slightly extending this, I would like to handle the properties of the bound object differently, such as, if the property is just a primitive type, just output it, but if its another object/array, then handle it specially.
Can this be done?
If anyone else is looking to bind a simple object's properties. You can do it like this...
<table>
<tbody data-bind="foreach: arrayOfObjects">
<tr data-bind="foreach: Object.keys($data)">
<td data-bind="text: $parent[$data]"></td>
</tr>
</tbody>
</table>
note: object.keys is not supported in older browsers, but you can use this to add backwards compatability http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With