AngularJS/Ionic–Can't将相同的数据添加到数组中

AngularJS/Ionic – Can't add identical data to an array

本文关键字:数据 添加 数组 Ionic Can AngularJS      更新时间:2023-09-26

我遇到了一个奇怪的问题(我对angular甚至JS都很陌生,但我相信这应该可以工作,因为我在终端中使用node测试了它,它很好)。我已经创建了一个按钮,基本上应该添加"hi"作为数组的一个条目。但是,它只添加一次,然后停止工作。我原以为它会继续加上"嗨"、"嗨"。。。等等——我应该提到这是使用"push"。

因此,我尝试了以下操作,获取最后一个条目的索引,然后添加"hi"作为新条目,如下所示:

$scope.attend2 = function() {
         arrayLength = $scope.eventAttending.length;
         $scope.eventAttending[arrayLength] = "Hi";
        };

我仍然有同样的问题。我首先输入了最后一个数组项的索引作为数据,这会很好,因为每次添加的数据都不同(例如eventAttending[1]=1,然后eventAttending[2]=2),然而,当它是相同的数据时,它似乎不起作用;例如,eventAttending[1]="hi",然后eventAttending[2]="嗨"——在这种情况下,我在数组索引1中得到"hi"。

感谢您的帮助,

Chris

尝试推送数组中的值:

$scope.eventAttending.push("Hi");

只需在控制器中定义一个空数组,并在按钮的点击事件上按下字符串消息

示例

angular.module('app', [])
.controller('myCtrl', function($scope) {
  $scope.hiArray = [];
  $scope.onClick=function(){
    $scope.hiArray.push('Hi');
  }
})
<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="app" ng-controller="myCtrl">
    <button ng-click="onClick()" >Add Hi</button> <br>
    {{hiArray}}
  </body>
</html>

请参阅Plnkr

您可以尝试使数组具有多维性:

$scope.eventAttending=[];
$scope.attend2 = function() {
         var arrayLength = $scope.eventAttending.length;
         $scope.eventAttending.push({arrayLength:"Hi"});
};

问题是在ng repeat中使用该数组,默认情况下,该指令使用内容来区分项。

您可以使用"track by"来更改用于跟踪元素的变量:

<div ng-repeat="item in items track by $index">{{item}}</div>