无法获取AngularJs中所选项目的索引

时间:2016-01-06 14:05:06

标签: angularjs angularjs-ng-change

我有一个下拉值,我使用一个下拉框来显示项目。我想处理click事件并打印数组中元素的索引。视图代码如下:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <link data-require="font-awesome@4.5.0" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
    <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script data-require="bootstrap@*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">     </script>
    <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myController">
    <select ng-options="item for item in items" ng-model="item" ng-change="handleClick($index)">
  </select>

</html>

在控制器上我有功能,但我没有选择索引。

// Code goes here

angular.module("myApp", []).

controller("myController", function($scope){
     $scope.handleClick = function(index){
     console.log("came inside the handleClick function with the currext index "+index);
    }
    $scope.items=["pradeep","praveen", "sagar","vinod"];
})

请让我知道我哪里出错了。链接到Plunkr - Link to Plnkr

1 个答案:

答案 0 :(得分:4)

使用$index时未定义

ngOptions - 您最好的选择是使用indexOf并找到索引:

<select ng-options="item for item in items" ng-model="selectedItem" ng-change="handleClick(selectedItem)">

和JS:

$scope.handleClick = function(selectedItem) {
    var index = $scope.items.indexOf(selectedItem);
}