Ferooz Khan
Ferooz Khan

Reputation: 93

Cannot read property in angular js

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

Upvotes: 0

Views: 214

Answers (2)

squiroid
squiroid

Reputation: 14037

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)

Upvotes: 0

krivtom
krivtom

Reputation: 24916

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 : [] };

Upvotes: 3

Related Questions