2016-01-06 75 views
2

我有一個下拉列表,其中包含我正在使用下拉框來顯示項目的值。我想處理click事件並打印數組中元素的索引。查看代碼如下:無法獲取AngularJs中所選項目的索引

<!DOCTYPE html> 
<html ng-app="myApp"> 
    <head> 
    <link data-require="[email protected]" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" /> 
    <link data-require="[email protected]" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" /> 
    <script data-require="[email protected]*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script> 
    <script data-require="[email protected]*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">  </script> 
    <script data-require="[email protected]" 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 - 使用ngOptionsLink to Plnkr

回答

3

$index沒有定義 - 你最好的選擇是使用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); 
}