Angular JS ng重复/添加到数组错误

Angular JS ng-repeat/adding to array bug

本文关键字:数组 错误 添加 JS ng 重复 Angular      更新时间:2023-09-26

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

这是ngRepeat的文档。