如何访问 AngularJS 中组合框的选定元素?

How can I access the selected element of a combobox in AngularJS?

我将一个数组放入组合框中,并希望在按下按钮时删除标记的元素(通过单击组合框中的元素选择)。如何访问所选元素?

我的html:

<div ng-controller="MyCtrl">
<select size="5">
    <option ng-repeat="element in elements">{{element}}</option>    
</select>
<button ng-click="removeSelected()">Delete selected</button>   

我的 js:

function MyCtrl($scope) {
    $scope.elements = [1, 2, 3];
    $scope.removeSelected = function () {};
}

这是我的 Fiddle

您需要使用 ng-options 而不是 ng-repeat

ng-options 是应用于父 select 元素的指令,如下所示:

<select ng-options="element for element in elements" ng-model="selected">
</select>

然后您可以继续通过 select 元素的 ng-model 访问活动 selection,在本例中为 selected - 并将其删除像这样:

$scope.removeSelected = function(){
    var index = $scope.elements.indexOf($scope.selected);
    $scope.elements.splice(index, 1)
};  

Updated fiddle.