例如:
<select ng-model="selectedCategory" ng-options="category as category.title for category in categories"></select>
显然,这不起作用:
<button ng-click="removeCategory($index)">remove</button>
如果不在转发器中,如何访问$ index?
答案 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];
}
}])