获取Angular中所选选项的$ index

时间:2013-04-22 20:25:58

标签: javascript angularjs

例如:

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

显然,这不起作用:

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

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

1 个答案:

答案 0 :(得分:7)

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

您的控制器可能如下所示 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];
  }
}])