Accessing the $index value from the selected option when using ng-change within a select element

Although there are similar questions out there, I couldn't find one that addresses my specific need:

  1. ngRepeat inside option-tag
  2. ngChange inside select-tag

I am trying to retrieve the index of the selected option. Here is a snippet of my code:

<select data-placeholder="Choose" ng-model="pp.sif" name="myname" ng-change="onChangeSifra()">
    <option ng-repeat="item in sif.what track by $index" value="{{item.SIF}}">
        {{item.LABEL}}
    </option>
</select>

The use of ngClick inside the option-tag does not work on Chrome and IE, so that's not a viable solution. Additionally, using ngOption instead of ngRepeat is not an option due to the nature of the array of objects within sif.what.

Any suggestions?

EDIT: For those suggesting the switch to ngOption, here's why it won't work for me. I'm iterating through something like this:

$scope.sif.what = [
    {SIF: 1, LABEL: "label 1", SAVED: "save me 1"},
    {SIF: 2, LABEL: "label 2", SAVED: "save me 2"},
    {SIF: 3, LABEL: "label 3", SAVED: "save me 3"},
]

Basically, in a combobox, the label is displayed as the label, the "sif" is set as the value, and ngModel represents the value of "sif". However, during ngChange, I require access to the entire object, particularly sif.what(index) or $index.

Thank you.

Answer №1

It may be tricky to return the index of the selected item without assigning it as the value of the option.

One possible solution is outlined below:

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

app.controller('ctrl', function($scope, $filter) {
  $scope.sif = {'what': [{'SIF':'A'},{'SIF':'B'},{'SIF':'C'}]};
  $scope.onChangeSifra = function(item){
     $scope.selectedItem = $filter('filter')($scope.sif.what, {SIF : $scope.pp.sif}, true)[0];
     $scope.selectedItemIndex = $scope.sif.what.indexOf($scope.selectedItem);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" />

<body ng-app="app" ng-controller="ctrl">
  <div class="col-lg-12">
    <select data-placeholder="Choose" ng-model="pp.sif" name="sif" ng-change="onChangeSifra()">
      <option ng-repeat="item in sif.what track by $index" value="{{item.SIF}}">
          {{item.SIF}}
      </option>
    </select>
    
    <p>Selected : {{pp.sif}}</p>
    <p>Index : {{selectedItemIndex}}</p>    
  </div>
</body>

Answer №2

Consider utilizing ng-options instead of ng-repeat for a better approach:

<select data-placeholder="Choose" ng-model="pp.sif" name="sif" ng-change="onChangeSifra()" ng-options="{index: idx, item:item.SIF} as item.SIF for (idx, item) in sif.what">
</select>

Answer №3

Insight : consider using the ngOptions attribute in place of ng-repeat.

Utilize the array.indexOf() method to determine the index of the selected item.

EXAMPLE

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

myApp.controller('MyCtrl',function($scope) {
    $scope.sif = {
      "what": [
        {
          "SIF":1
        },
        {
          "SIF":2
        },
        {
          "SIF":3
        }
      ]
    };
  $scope.onChangeSifra = function(selectedItem) {
    console.log($scope.sif.what.indexOf(selectedItem));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select data-placeholder="Choose" ng-model="pplsif" name="sif" ng-change="onChangeSifra(pplsif)" ng-options="item.SIF for item in sif.what">
</select>
</div>

Answer №4

Feel free to give this login a shot

<select ng-model="optIndex" ng-change="getIndex()">
<option ng-repeat="opt in opts" value={{$index}}></option>
<select>

$scope.getIndex = function(){console.log($scope.optIndex);}

You are now able to retrieve your index using this code snippet :)

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

Tips for incorporating a last or recently visited feature similar to Google Docs using MongoDB

Within my database, I have two collections: users and projects. These collections share a many-to-many relationship. One user can be associated with multiple projects and one project can be assigned to multiple users. In the user object, I store an array o ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Angular component with optional one-way binding for version 1.5 and above

Copied from the official AngularJS 1 documentation: To make a binding optional, simply add ?: <? or <?attr. What are the differences between the optional and non-optional one-way bindings? I can't seem to find the dissimilarities for the op ...

The behavior of Quasar's q-drawer is quite unpredictable

Having made the transition from Vue.js 2 with Vuetify to Vue.js 3 with Quasar due to Vuetify not officially supporting Vue.js 3 yet, I am utilizing q-drawer and its mini property. This allows me to toggle between the mini state and the normal expanded stat ...

Tips for identifying when v8 heap utilization in Node.js is nearing its limit

Currently, my script includes the following code: const v8 = require('v8'); let heap = v8.getHeapStatistics(); let usage = 100 / heap.heap_size_limit * heap.used_heap_size; if (usage > 90) { console.log(`V8 heap usage close to the limit ...

Button placed within a jade table cell

I'm struggling to make a button appear in each row of the table. I am new to working with Jade and Node.js, so I can't seem to figure out why it's not showing up. Here is my Jade file: html head body table.table.table(border='1 ...

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

What is the process for extracting dates in JavaScript?

I need help extracting the proper date value from a long date string. Here is the initial date: Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time) How can I parse this date to: 2020-08-30? Additionally, I have another scenario: Tue Aug 25 ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Difficulty capturing emitted events from child components in Vue.js2

Currently, I'm working on developing a Bootstrap tabs component using Vuejs. The tabs component is divided into two parts - the parent tabs-list component that contains multiple tab-list-item components. Take a look at the code for both these componen ...

Several onclick events on a single webpage

Despite numerous attempts and hours of reading, I am still unable to figure this out. There are two different types of card elements, each with a selection of 15 different color choices. Aside from using "a", is there anything else I can try to solve this? ...

Issue with grunt-crx task detected

In my Gruntfile, I've integrated the grunt-crx task as shown below: crx: { packExtension: { src: "../build/unpacked", dest: "../build/dist" } } Whenever I execute the crx task on its ow ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Is it possible for the angular $resource module to return data in a format other than JSON?

I am seeking to extract data from a website that offers an API for retrieval. However, I am unsure about the format of the data. Is it in JSON? Is it an array or an object? Could someone take a look and provide insights? Cheers! https://i.sstatic.net/xMSm ...

What is the proper way for the curry function to function effectively?

Here's a function that I came across: function curry(fn) { var args = [].slice.call(arguments, 1); return function() { return fn.call(this, args.concat([].slice.call(arguments))); }; } I always thought this was the correct way fo ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...

In the `angular-daterangepicker.js` file, add the option "Single Date" to the list of available ranges

I'm currently working on implementing a new feature that is similar to the "Custom Range" option, but with a twist. I want to provide users with the ability to choose only one date, much like a "Single Date Picker". By adding this new option under "Cu ...

Ajax is known for inundating servers with requests at a rapid rate, causing a significant

I am running an application that sends multiple requests per second to fetch data from API and return responses to clients. The process flow is as follows: Ajax sends a request View sends a request API returns response for view View returns response for ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...