Hello, I am currently working on a project using AngularJS ng-repeat to generate a dynamic list of cities. The user has the ability to build this list client-side by selecting cities from a list on the left side of the page and clicking the "Add City" button to add them to another list on the right. The issue I'm facing is that when a city is added to the right list, the $index values for the list items remain at zero.
Below is the code snippet where the cities are dynamically added:
<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> <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>
Here are the relevant JavaScript functions for adding a city to the list dynamically:
$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 };
I am wondering if there is something missing in either the HTML or JavaScript functions that would allow the ng-repeat list to update the $index value after a city is added. Any help or suggestions would be greatly appreciated.