Reputation: 15583
I want to add ingredient to a product object.
<ul data-bind="foreach: products">
<li data-bind="text: name"></li>
<li>
<ul data-bind="foreach: ingredients">
<li data-bind="text: name"></li>
</ul>
</li>
</ul>
<script>
var viewmodel = {
products: ko.observableArray([])
};
ko.applyBindings(viewmodel);
</script>
If I do the code below, it works fine:
viewmodel.products.push({
name:"product name",
ingredients:[{name:"ingredient 1"},{name:"ingredient 2"}]
})
But now I need to access the last product added and add an ingredient.. would be something like that:
viewmodel.products[0].ingredients.push({name:"ingredient 3"})
But when I do that, the error 'TypeError: Cannot read property 'ingredient' of undefined' throws.
Upvotes: 1
Views: 105
Reputation: 3558
I wrote a fiddle for you. It works!
To access products
you must wrote products()[0]
, but not products[0]
, because ()
means get value
this fiddle is in new knockout style
http://jsfiddle.net/hBsFM/3/
and this fiddle in the style that you use
http://jsfiddle.net/zjF6c/
Upvotes: 1