The console is showing an 'undefined' return value for the $index variable in Angular

Hi there,

I've encountered a problem with some code I wrote, and I'm hoping someone can help me figure out what's going on.

This particular snippet of code is supposed to run when the menu buttons are clicked.

$scope.show = function($index){
    console.log($index);
};

However, when I check the console log, it's always returning 'undefined'.

If anyone has any insights or suggestions, I would really appreciate the help.

You can view the JS bin for reference: https://jsbin.com/keteji/edit?html,js,console,output

Any assistance you can provide would be greatly valued.

Thank you in advance!

Answer ā„–1

$index represents the iterator offset of the repeated element, accessible within each template instance in ng-repeat

If your menu list is stored as dataArray, you can utilize ng-repeat to display the iterations in the view

Give this a try:

var app = angular.module('angularApp',[]);

app.controller('AppController',['$scope',function($scope){
  $scope.dataJson = dataArray;
//   console.log($scope);
  
  
  $scope.show = function($index){
    alert($index);
  };
  
  
  $('.nav li').click(function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
  });
  
}]);

var dataArray =[
  {
    "id":1,
    "name":"Home",
    "visible":true
  },
  {
    "id":2,
    "name":"Profile",
    "visible":false
  },
  {
    "id":3,
    "name":"Messages",
    "visible":false
  }
];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="angularApp">
  <div ng-controller="AppController">
    
    <ul class="nav nav-pills">
      <li role="presentation" ng-repeat="d in dataJson" ng-click="show($index)"><a href>{{d.name}}</a></li>
      
    </ul>

    <div class="row">
      
      <div class="col-md-12" ng-repeat="pages in dataJson">
        <h3 ng-show="pages.visible">
          {{pages.name}}
        </h3>
      </div>  
      
      
    </div>
  
  </div>
  
  
</body>

Answer ā„–2

$index is a special attribute within the ngRepeat directive scope.

It's not accessible within controller scopes.

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

Localhost being injected into the pathname by Axios

I am trying to implement an axios request using their official documentation. Here is my code snippet: const REFERRAL_API_URL= "https://referrals.gen.com" export function createReferral() { axios({ data: {}, headers: { 'Content-Type ...

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

How can successful AJAX requests access PHP data?

Do you know how I can run a basic PHP code using AJAX and receive the data back from the PHP page in the AJAX success function? I am facing an issue where I am not getting anything in the AJAX success callback from the PHP page, and it's really bothe ...

Attempting to select an image with the intention of triggering a modal to appear through an ajax

Hi there, I recently started coding and I'm facing an issue that I can't seem to solve. I want to set it up so that when you click on an image, a modal opens corresponding to the img tag, and then the modal click event triggers a method. The prob ...

Having trouble getting sweet alert to work with my PHP script

Iā€™m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if an ...

Next.js encountered an issue: React.Children.only function was expecting to receive only one React element child, but received more

I have created a component named Nav located in the components directory. Here is the code for it: import Link from 'next/link'; const Nav = () => { return( <div> <Link href="/"> <a> Home </a> ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Passing data to child Vue component and iterating through it

Working with the axios call to fetch data from an API has been my current challenge. I am aiming to integrate the Home and ListItem components seamlessly. <template> <div> <list-item v-for="idea in ideaList" :key="idea.id" ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

Executing a single Function within the UseEffect Hook

Can anyone assist me with solving this code puzzle? I have a carousel element that includes icons for moving to the previous and next slides. Whenever these icons are clicked, a specific function needs to be triggered within the useEffect() hook. The spec ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

"Incorporate a personalized dropdown menu (using the datatables plugin) in the designated design structure

Is it possible to add a dropdown list next to the search field in the datatables plugin without positioning it outside where the plugin is initialized? I want to have a custom dropdown list with fixed values, similar to this: https://i.sstatic.net/Fm4zs.pn ...

Deciphering JSON data into PHP arrays and variables: A step-by-step guide

As a PHP beginner, I'm struggling to grasp certain concepts related to extracting data from POST requests in PHP. Let me describe my code and the issue I'm facing: I have a serialized array that I convert to JSON before sending it via ajax to PH ...

Error: Props variable is not defined in ReactJS

I am currently working with react js and facing an issue where props are not defined. Below is my class: import React, { Component } from 'react'; const InputHeight = { height: '50px', } function clearData() { this.refs.inpu ...

ASP.NET ensures that the entire page is validated by the form

Is it possible to validate only a specific part of the form instead of the entire page? Currently, when I try to validate textboxes on the page, the validation is applied to all textboxes. Here are more details: https://i.stack.imgur.com/eowMh.png The c ...

Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently: var arr1 = [1,2,3,4] var arr2 = [null, 99, null, null] arr2.map((item) = ...

Implementing Role-Based Access Control (RBAC) with an express backend and passport authentication

I am currently in search of an RBAC package or a demonstration using middleware on Express router. My goal is to establish different roles such as admin, manager, and user during registration, and then verify these roles with each backend request. Althou ...

Utilizing JavaScript for Interactive Check/Uncheck Feature in TreeView Nodes

I am currently utilizing the following JavaScript for implementing Check/Uncheck functionality for TreeView nodes checkboxes. The treeview contains three levels: parent, child, and siblings. Although the JavaScript code functions properly, I am in need ...