The dynamic list in AngularJS using ng-repeat always starts at index zero

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>&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>

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.

Answer №1

Consider incorporating track by $index into your ng-repeat loop. For a detailed example, check out this resource:

Answer №2

It appears that the index is only necessary for retrieving the city from the array filter.selectedCities. However, using the city directly eliminates the need for the index:

ng-click="addToCityFavs(city);"

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize DOM to attach a button onto an image

I am looking to add buttons onto images using DOM manipulation. Each image will have multiple buttons that, when clicked, will delete the image. I am aiming for a functionality similar to this example - JSFiddle This is the code I have attempted so far: ...

Issue with Firebase Cloud function not terminating despite receiving a 204 response code

Currently, I am developing a cloud function to manage server operations for a gaming panel. Everything seems to be functioning correctly except that after the request is completed, it fails to trigger the expected "data", "end", or "closed" events which ...

AngularJS - developing a unique directive with customized attributes embedded in the templateUrl

In my arsenal of text formatting templates, I have files named frecuencia-dia.html and frecuencia-mes.html, among others. My goal is to dynamically call a template using the attributes tipo (representing text type) and clave (variable scope). <ng-form ...

Utilizing Vue's dynamic component feature to create event listeners

Issue: My current project involves creating a versatile table component that can be utilized by other components to display tabular data. Each cell in this table could contain one of three possible values: Text HTML Component While I have successfully im ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Utilizing React Redux Loading Bar: Error - Unable to access property 'default' of an undefined object

UPDATE After updating and installing the library with its newer package, I encountered the following error: TypeError: Cannot read property 'default' of undefined Function.mapStateToProps [as mapToProps] node_modules/react-redux-loading-bar/buil ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Top method for retrieving CSS variable in a customized Angular directive

I have a question regarding the process of converting the statement below to Angular's renderer2: this.elementRef.nativeElement.style.setProperty( '--primary-color ' , '#455363' ) The above statement modifies a CSS variable in the ...

Is there a way to modify the appearance of a particular element in ng-repeat?

On my website, I am using ng-repeat to display various dish postings. I want to trigger a modal to open when I click on a dish, showing the specific data for that dish. To achieve this, I'm assigning each dish a modal div with a unique ID (dish-$index ...

Error message: "Unable to POST image with Node/Express (React frontend) while attempting to upload

I am a beginner in Node.JS and currently working on developing a MERN movie ticket booking system. The front-end code snippet provided below showcases the function responsible for uploading an image for a specific movie: export const uploadMovieImage = ( ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

When attempting to perform $save() on $resource, a TypeError is thrown indicating that Object #<g> does not contain the method 'push'

Resource factory: .factory('WorkerRepository', function($resource){ return $resource('workers/:id', {id:'@id'}); }) Controller: .controller('ListController', function($scope, WorkerRepository){ var workers ...

Extracting JavaScript variable data to PHP using Ajax technology

I've been trying to save latitude and longitude values in PHP variables, but I'm having trouble. Here is the code I'm using. Can anyone please help me figure out why these values are not being stored in PHP variables: Code: <!DOCTYPE h ...

Tips for utilizing useQuery in React JS class component:

Currently, I'm working on an app that is exclusively built using React JS class components. Since UseQuery only functions with function components and the Query tag has been deprecated, I'm facing some challenges in getting the data I need. Any s ...

Personalize the highcharts tooltip to display date and time

I'm working on a new project where I need to display a graph like the one you can see here: http://jsfiddle.net/Kc23N/ One issue I am facing is that when clicking on a point (tooltip), I want to show a date in a readable format rather than just the v ...

Discovering iBeacon using Web Bluetooth

I've been experimenting with the new web bluetooth feature, using one of these estimote beacons: Having identified the uuid for my beacon, here is the angular app code I'm currently utilizing (with references to $scope and $window): $scope.runB ...

undefined childrenWithProps in React with JavaScript

GalleryPhotosVideos.js class GalleryPhotosVideos extends React.Component { constructor(props) { super(props); this.state = { data3 }; } render (){ const childrenWithProps ...