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

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

本文关键字:index 列表 ng-repeat 动态 构建 AngularJS      更新时间:2023-09-26

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

以下是动态添加城市的 ng 重复列表:

<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。有关示例,请参阅此链接: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;