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>
            <h1>{{list.name}}</h1>
        </header>
        <div ng-repeat="list in notepadCtrl.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
            <ul>
                <li ng-repeat="item in list.items">

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

Answers


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

Search




Leave an answer