Thian Kian Phin Thian Kian Phin - 1 month ago 14
AngularJS Question

angularjs pass index of array into ng-change function

I use ng-select to populate my options, but I want to pass the selected index, what should be in the ng-change function?

like if the user selected

b
I will get
1
which is the second index of the array.

http://jsfiddle.net/kqcrL5j3/

<select
ng-options="p as a for a in alpa"
ng-model="selected" ng-change="detectChange('what to pass index here?')"></select>

Answer

change your code like this,

<select ng-options="a for a in alpa" ng-model="selected" ng-init="selected='a'" ng-change="detectChange(selected)"></select>

You can pass the whole selected object and find the index like this,

  $scope.detectChange = function(selected_index){
       var indexno =  $scope.alpa.indexOf(selected_index );
       console.log(indexno)
    }

DEMO

Comments