Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the $index of selected option in Angular

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?

like image 577
TaylorMac Avatar asked Apr 22 '13 20:04

TaylorMac


1 Answers

You shouldn't need to keep track of the index, simply remove the selectedCategory from the categories 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];
  }
}])
like image 80
Ryan Q Avatar answered Oct 18 '22 16:10

Ryan Q