AngularJS 动态构建的 ng-repeat 列表,$index 始终为零

AngularJS ng-repeat list built dynamically,$index is always zero

我正在使用 AngularJS ng-repeat 创建城市列表。该列表由用户在客户端动态构建。用户从页面左侧的列表中选择城市,单击 "Add City" 按钮,城市将添加到右侧的列表中。 ng-repeat 在两个列表中,但是当一个城市被添加到右边的列表中时,列表项的 $index 值不会更新。 $index 值全为零。

这是动态添加城市的 ng-repeat 列表:

<div ng-repeat="(key, value) in filter.selectedCities | groupBy:'country'" class="text-left">
    <div ng-repeat="(key2, value2) in value | groupBy:'state'" class="text-left">
        <span class="label label-default">{{key}}   </span>&nbsp;<span class="label label-danger" ng-show="key2.length">{{key2}}    </span>
        <ul class="nav nav-pills">
            <li class="selectedpill" ng-repeat="city in value2">
                <div class="pull-left">
                    <span class="indent8">{{ city.label | characters:24 :true}}</span>
                </div>
                <div class="pull-right">
                    <i class="fa fa-heart pointer" ng-click="addToCityFavs($index);" ng-class="{'maroonzheimer' : checkFavCity(city)}" ng-hide="savingCityFav" title="Add To Favorites"></i>
                    <i class="fa fa-spinner fa-spin" ng-show="savingCityFav"></i>
                    <i class="fa fa-times fa-lg pointer" ng-click="removeCity(city)" title="Remove City"></i>
                </div>
            </li>
        </ul>
    </div>
</div>

以下是 JavaScript 用于将城市动态添加到列表的函数:

  $scope.addSelectedCity = function () {
    if ($scope.selectedCity && $scope.selectedCity.value) {
      $scope.addCity($scope.selectedCity);
      $scope.cityValidationError = false;

    } else { $scope.cityValidationError = true; }
    $scope.tempSelectedCity = null;
    $scope.selectedCity = null;
  }

  $scope.addCity = function (city) {
    if (city && city.city && !$scope.checkCityExists(city)) {
      $scope.filter.selectedCities.push(city);
    }    
  }

$scope.addToCityFavs = function (index) {
  var city = $scope.filter.selectedCities[index];
  var exists = false;

  for (var i = 0; i < $scope.filter.favs.CityList.length; i++) {
    if ($scope.filter.favs.CityList[i].city.value == city.value) {
      exists = true;
    }
  }

 if (!exists) {
   $scope.savingCityFav = true;
   var fav = { id: 0, active: true, ruser_id: 0, city: city }; 

我是否需要在 HTML 或 JavaScript 函数中添加一些东西来让 ng-repeat 列表在一个城市被添加到列表后更新 $index 值?

如果有人能提供任何帮助,我将不胜感激。

尝试将 track by $index 添加到 ng-repeat。 请参阅此 link 示例:https://egghead.io/lessons/angularjs-index-event-log

看来索引只需要从数组中获取城市filter.selectedCities。但是你不需要索引,因为你可以直接使用城市:

ng-click="addToCityFavs(city);"

$scope.addToCityFavs = function (city) {
  //no longer needed -> var city = $scope.filter.selectedCities[index];
  var exists = false;