1

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.

3
  • Could you create a fiddle to demonstrate your issue please? Commented Aug 13, 2012 at 13:27
  • @llya Sorry, groups was to be products. I just fix it in description. Commented Aug 13, 2012 at 13:52
  • @WickyNilliams Dont know why, but I cant insert HTML code in fiddler. Commented Aug 13, 2012 at 13:53

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.