Get the $ index of the selected option in Angular

For instance:

<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 can I access the index $ index if not in the repeater?

+5
source share
1 answer

You do not need to track the index, just remove the selected category from the category model in the removeCategory function:

Your controller might look like this: 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];
  }
}])
+7
source

All Articles