例如:
<select ng-model="selectedCategory" ng-options="category as category.title for category in categories"></select>
显然,这是行不通的:
<button ng-click="removeCategory($index)">remove</button>
如果不在中继器中,如何访问 $index?
例如:
<select ng-model="selectedCategory" ng-options="category as category.title for category in categories"></select>
显然,这是行不通的:
<button ng-click="removeCategory($index)">remove</button>
如果不在中继器中,如何访问 $index?
您不需要跟踪索引,只需从 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];
}
}])