Home Ask Login Register

Developers Planet

Your answer is one click away!

ajm February 2016

How to add objects to a key within another dynamically created object in Angular?

I'm using Angular to create a shopping list app. For testing purposes I have two pre-created lists each with pre-created names and items. Eventually the user will initially be presented with an empty list to which they can add items. Then they can add a new list for new items. So far I have the ability to add and remove items to and from the existing list, and I can add a new list. But I can't add new items to a newly created list. I get a "Cannot read property 'push' of undefined" error for the line list.items.push(this.item);. My guess is that when I create a new list, there is no items key added to it and that's why it's undefined. I tried creating an items key when I create a new list, but I couldn't get it to work. That might not be the problem anyway.

Working fiddle is at https://jsfiddle.net/sueanna/vj7heyt7/1/

EDIT: I added some CSS to the fiddle to help with visuals - https://jsfiddle.net/sueanna/vj7heyt7/2/

Here's the markup:

<div ng-app="notepadApp">
    <div ng-controller="notepadController as notepadCtrl">
        <header ng-repeat="list in notepadCtrl.lists">
            <div>Delete list</div>
        <div ng-repeat="list in notepadCtrl.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
                <li ng-repeat="item in list.items">

                        <input type="checkbox" ng-model="item.checked">
                    <form name="itemForm" ng-submit="itemCtrl.removeItem(list, $index)">
                        <input type="submit" value="remove">


Claies February 2016

You create a new list in two places; once on controller initialization, and again in the addList function.

In both places, you need an items array to match the structure being used by the other list. In both places where you create a new list, change your initialization code to this.list={items:[]}; in order to ensure that there is an items [] to push into.

Post Status

Asked in February 2016
Viewed 2,501 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life