Angular JS ng-repeat/adding 数组错误

Angular JS ng-repeat/adding to array bug

我是 AngularJS 开发的新手,我在测试一个非常简单的脚本时遇到了一个我无法完全破译的错误。

当用户输入内容并按下回车键时,我的脚本只是将一个字符串从输入框中添加到数组中,然后在输入框下方使用 ng-repeat 打印出所有项目。

脚本似乎工作正常,除非我尝试添加列表中已有的值。如果我添加一个已经再次添加的值,脚本将停止添加项目,即使我返回并尝试新值也是如此。

这是我的 javascript:

    var myApp = angular.module('myApp',[]);
    myApp.controller('ctrl1',function($scope){
        $scope.list = [];

        $scope.addItem = function(keyEvent){
            if(keyEvent.which === 13)
            {

                if(angular.isDefined($scope.name) && $scope.name!='')
                {
                    $scope.list.push($scope.name);
                    $scope.name = '';
                }
            }
        }

    });

这里是 html 部分:

<div ng-controller = "ctrl1">
<input type = "text" ng-model = "name" placeholder = "Enter item to add to list" ng-keypress = "addItem($event)"/>
<ul ng-repeat = "item in list">
<li>{{item}}</li>
</ul>
</div>

有谁知道是什么导致了这个错误? 谢谢

默认跟踪功能(根据项目的标识跟踪项目)不允许数组中的重复项目。这是因为当存在重复时,不可能在集合项和 DOM 元素之间保持一对一的映射。使用 track by $index 允许条目中出现重复项。执行以下操作:

<div ng-controller = "ctrl1">
   <input type = "text" ng-model = "name" placeholder = "Enter item to add to list" ng-keypress = "addItem($event)"/>
   <ul ng-repeat = "item in list track by $index">
      <li>{{item}}</li>
   </ul>
</div>

HerengRepeat 的文档。