javascript 获取 Angular 中所选选项的 $index

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16156086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:29:47  来源:igfitidea点击:

Get the $index of selected option in Angular

javascriptangularjs

提问by TaylorMac

For example:

例如:

<select ng-model="selectedCategory" ng-options="category as category.title for category in categories"></select>

Obviously, this will not work:

显然,这行不通:

<button ng-click="removeCategory($index)">remove</button>

How could $index be accessed if not in a repeater?

如果不在中继器中,如何访问 $index ?

回答by Ryan Q

You shouldn't need to keep track of the index, simply remove the selectedCategory from the categories model in the removeCategory function:

您不需要跟踪索引,只需从 removeCategory 函数中的类别模型中删除 selectedCategory 即可:

Your controller might look like this JSFiddle:

您的控制器可能看起来像这个JSFiddle

app.controller("myCtrl", ['$scope', function($scope){
  $scope.model = {
    selectedCategory: {},
    categories: [
        {title: "Cat1"},
        {title: "Cat2"}
    ]
  }
  //init
  $scope.model.selectedCategory = $scope.model.categories[0];

  $scope.removeCategory = function(){
    var ind = $scope.model.categories.indexOf( $scope.model.selectedCategory );
    $scope.model.categories.splice( ind, 1 );
    $scope.model.selectedCategory = $scope.model.categories[0];
  }
}])