我正在使用AngularJS ng-repeat来创建城市列表。该列表由用户在客户端动态构建。用户从页面左侧的列表中选择城市,单击“添加城市”按钮,城市将添加到右侧的列表中。 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> <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值?
我会感激任何人都能给予的帮助。
答案 0 :(得分:2)
尝试将track by $index
添加到ng-repeat
。
请参阅此链接以获取示例:https://egghead.io/lessons/angularjs-index-event-log
答案 1 :(得分:1)
所以看起来索引只需要从数组filter.selectedCities
获取城市。但是你不需要索引,因为你可以直接使用城市:
ng-click="addToCityFavs(city);"
$scope.addToCityFavs = function (city) {
//no longer needed -> var city = $scope.filter.selectedCities[index];
var exists = false;