无法读取角度js

时间:2015-06-22 15:52:54

标签: javascript html angularjs

这是我的脚本文件

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);
             };}

这是我的html文件。

<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>

当我点击添加我按钮时,我收到错误

 TypeError: Cannot read property 'items' of undefined

我无法弄清楚错误及其发生的原因。请帮助我,我是angular js的新手

2 个答案:

答案 0 :(得分:3)

发生错误是因为您的user属性为null:

$scope.user = null;

将其更改为理想情况下具有items属性的实际对象:

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

答案 1 :(得分:0)

如果您有$scope.user = null;

,那么项目在哪里很简单

如此简单,添加一件事

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

然后使用$scope.user.items.push(data)