0

This is my script file

app.controller('userController', function PostController($scope, userFactory) {
$scope.users = [];
        $scope.user = { items : [] };
        $scope.editMode = false;

        $scope.addItem = function () {

                $scope.user.items.push({
                    Name: $scope.newItemName,
                    Value: $scope.newItemValue
                });
            };

         $scope.deleteItem = function (index) {
                 $scope.user.items.splice(index, 1);
             };}

This is my html file.

<div class="form-group">
    <ul class="nav">
       <label for="title" class="col-sm-2 control-label">Items</label>
       <div class="col-sm-10">

       <input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemName" required placeholder="name of new item...">
       <input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemValue" required placeholder="name of new item...">
           </div>
       <button ng-click="addItem()">Add Me</button>
       <li ng-repeat="item in user.items">
           <a href="#">{{item.Name}}</a>  <a ng-click="deleteItem($index)" class="delete-item">x</a>
       </li>
    </ul>
</div>

When I Click add me button i get an error as

 TypeError: Cannot read property 'items' of undefined

I cant figure out the error and why it occurs. Please help me I'm new to angular js

2
  • Your $scope.user = null; should be comething else like $scope.user = {}; Commented Jun 22, 2015 at 15:55
  • its because your "items" object doesn't exist OP. you're trying to loop through variable that is NULL Commented Jun 22, 2015 at 15:59

2 Answers 2

3

The error occurs because your user property is null:

$scope.user = null;

Change it to an actual object which ideally has items property:

$scope.user = { items : [] };
Sign up to request clarification or add additional context in comments.

3 Comments

hehe you beat me by few seconds :D +1 for you :)
@FeroozKhan are you sure you updated everything? Here is a link to a working plunker
Is it just me, or I'm not getting any errors in the codepen link that you provided?
0

Simple where is items if you have $scope.user = null;

so simple do one thing add

$scope.user = {items:[]};

and then use $scope.user.items.push(data)

1 Comment

i have editing my script file the same error occurs.. @squiroid

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.