I'm using AngularJS ng-repeat to create a list of cities. The list is being built dynamically client-side by the user. The user selects city from a list on the left side of the page, clicks the "Add City" button, and the city is added to a list on the right. The ng-repeat is in both lists, but when a city is added to the list on the right, the $index value for the list items does not update. The $index values are all zero.
Here's the ng-repeat list where the cities are added dynamically:
<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 JavaScript functions used to add a city dynamically to the list:
$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 };
Do I need to add something to the HTML or JavaScript functions to get the ng-repeat list to update the $index value after a city has been added to the list?
I'll appreciate any help anyone can give.
$index
is inng-click="addToCityFavs($index);"
. And you sayaddToCityFavs
is always called with0
? Maybe you have only one city per state. Please note that$index
refers tocity in value2
, so you will have lots of cities with the same index anyway. – zeroflagL Jan 19 '15 at 18:51$index
0
? Or to put it differently: How do you know it's zero? – zeroflagL Jan 19 '15 at 19:42