Error message: "Index is not defined when using ng-repeat in AngularJS

I have a challenge toggling the button on and off within an ng-repeat. The 'View on Map' function works fine, but when I switch to 'Remove Marker', it throws an error 'ReferenceError: passedIndex is not defined' in the console log. Any suggestions for resolving this issue?

HTML:

            <li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize">
              <div class="categoryImg">
                <img src="img/csvIcon.png" />
                <img src="img/shpIcon.png" />
              </div>
              <div class="categoryDesc">
                <p>{{communityTheme.THEMENAME}}</p>
                <a href="" ng-hide="communityTheme.visibility" ng-click="getMapData(communityTheme.QUERYNAME, $index)">View on Map</a>
                <a href="" ng-show="communityTheme.visibility" ng-click="removeMarker(communityTheme.QUERYNAME, $index)">Remove Marker</a>
              </div>
            </li>

JS:

        $scope.getMapData = function (msg, passedIndex) {
                map.addLayer(cities);

                $scope.Lng.length = 0;
                $scope.Lat.length = 0;
                $scope.dataLatLng.length = 0;

               queryNameUrl = 'https://developers.onemap.sg/publicapi/themeapi/retrieveTheme?queryName=' + msg +
               '&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjMsInVzZXJfaWQiOjMsImVtYWlsIjoicHVibGljQXBpUm9sZUBzbGEuZ292LnNnIiwiZm9yZXZlciI6ZmFsc2UsImlzcyI6Imh0dHA6XC9cL29tMi5kZmUub25lbWFwLnNnXC9hcGlcL3YyXC91c2VyXC9zZXNzaW9uIiwiaWF0IjoxNTQwOTI5OTE2LCJleHAiOjE1NDEzNjE5MTYsIm5iZiI6MTU0MDkyOTkxNiwianRpIjoiYjVkNmZkNGJhOWJiNGJiM2FkNWQzN2ZhNTAzMGIxYWEifQ.YQdfV43wrg8dX-He7-mwIL2Qhjsexq0tgNu5RotAdu4';
               $http.get(queryNameUrl).then(function(response) {
                 $scope.apiResult = response.data.SrchResults;
                 $scope.apiResult.splice(0,1);
                 console.log($scope.apiResult)

                       for (var i= 0; i < $scope.apiResult.length; i++) {
                            if ($scope.apiResult[i].Type == "Point"){
                              $scope.apiResult[i].visibility = true;
                              console.log($scope.apiResult)
                              $scope.dataLatLng.push($scope.apiResult[i].LatLng)
                              $scope.Lat.push($scope.dataLatLng[i].split(',')[0]);
                              $scope.Lng.push($scope.dataLatLng[i].split(',')[1]);
                              L.marker([$scope.Lat[i], $scope.Lng[i]], {icon: greenIcon}).bindPopup($scope.apiResult[i].DESCRIPTION).addTo(cities);
                            }
                              // else if ($scope.apiResult[i].Type == "Polygon"){
                              //       $scope.PolyLine.push($scope.apiResult[i].LatLng)
                              //       console.log($scope.PolyLine)
                              //       // for (var i = 0; i < $scope.PolyLine.length; i++) {
                              //       //     $scope.polyLineCord.push($scope.PolyLine[i])
                              //       //     // console.log($scope.polyLineCord)
                              //       // }
                              //   }
                       }
               })
               if($scope.community[passedIndex].visibility)
                {
                  $scope.community[passedIndex].visibility = false;
                }
               else{
                 $scope.community[passedIndex].visibility = true;
               }
        }

Remove Marker:

        $scope.removeMarker = function ($index) {

            if($scope.community[passedIndex].visibility)
             {
               $scope.community[passedIndex].visibility =false;
               cities.clearLayers();
             }
            else {
              $scope.community[passedIndex].visibility = true;
            }
        }

Thank you in advance for any assistance!

https://i.sstatic.net/YOWgG.png

Answer №1

Make sure to utilize track by $index

 <li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize track by $index">

Additionally, replace $index with passedIndex in your removeMarker function

$scope.removeMarker = function (passedIndex) {

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

What is the proper method for implementing respond_to with JSON data?

I find myself in a bit of a dilemma: I'm currently developing a centralized controller based on the guidance provided in this query and am encountering some confusion regarding the functionality of the respond_to method. In an API::Controller, my cod ...

Connecting Ember controllers with views/elements

As a developer with an Angular background, I am relatively new to Ember. Let's consider a scenario where there are multiple elements, each containing different sets of data. #elem1 10 #elem2 20 #elem3 30 My objective is to link each of these indiv ...

Enhancing infinite scroll functionality with ajax integration

After implementing a method to enable infinite scroll on my website using the following function: window.onscroll = yHandler; function yHandler(){ var wrap = document.getElementById('wrap'); var contentHeight = wrap.offsetHeight; var yOffset = w ...

The Ladda spin animation continues spinning for an additional second after the stop() function is called

I employ the ladda spinner in this manner: var l = Ladda.create(document.getElementById('ladda-test')); l.start(); l.stop(); console.log('ladda is stoped'); The issue I am facing is that following the execution of l.stop(), the animat ...

External variable accessing the getjson function

I have a question about optimizing the usage of the title variable within the getJSON function. Here's a sample code snippet that I'm working with: for (var x = 0; x < temp_addresses.length; x++) { var title = temp_addresses[x].title; ...

Execute the function when the element comes into view

Is there a way to create a function that will automatically attach itself to an element when it comes into view? I have multiple elements on my page - element1, element2, and element3. Instead of using a large if statement, I would like to write a functio ...

Customizing the MUI X Sparkline: Incorporating the percentage symbol at the end of the tooltip data within the MUI Sparklinechart

Presented below is a SparklineChart component imported from MUI X: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-chart ...

Leveraging datatables for efficient table searching in Asp.net MVC

When using datatables to search a table, I encountered an issue where adding another table row caused some problems as datatables requires the same number of rows and columns. Is there a workaround for this? I really want to utilize datatables but also nee ...

Fundamental Guidelines for Firebase

I've recently started working with Firebase and I'm encountering some issues with the security rules. My project is a blog website where visitors can read posts, users, and comments without being logged in. However, logged-in and verified users ...

What is the method for sending these variables via POST?

The code snippet referred to as New script is designed to produce two integer variables anchor and signed. I am interested in replacing the Old script with the New script, but there are significant differences between them. Inquiry How can I send/post t ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

I am experiencing an issue with AngularJS where it is not retrieving JSON data

I have been working on a custom service and trying to get it to return the desired JSON data, but I am having trouble getting any results. I've tried everything I can think of, but nothing seems to be working. Does anyone have any idea what I might be ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Modifying the color temperature or warmth in Three.js can enhance the visual aesthetics

In my three.js project, I've set up a room scene with various lights added to it. Features such as exposure, power, and height adjustments have been included in the setup. You can view the progress so far by visiting this link. My next goal is to i ...

Generate random images and text using a script that pulls content from an array

My goal is to have my website refresh with a random piece of text and image from an array when a button is clicked. I have successfully implemented the text generation part, but I am unsure how to incorporate images. Here is the current script for the text ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

`Enhance Image with a Fresh Hue`

Let me explain my dilemma: I'm dealing with a two-tone png image - one tone is black and the other is transparent. Right now, I'm relying on the background color attribute to dynamically change the color of the transparent section. However, I ...

Limit search to retrieve specific items based on pointer in JavaScript using Parse.com

BlogApp.Collections.Blogs = Parse.Collection.extend({ model: BlogApp.Models.Blog, query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", "xMQR0A1Us6").descending('createdAt').limit(9) }); The code snippet above doesn't seem ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...