简体   繁体   中英

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

I put an array into a combobox and want to delete the marked element (selected via click on element in combobox) when pressing a button. How can i access the selected element?

my html:

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

my js:

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

Here's my Fiddle .

You need to make use of ng-options instead of ng-repeat .

ng-options is a directive which is applied to the parent select element, like so:

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

You can then go ahead and access the active selection through the ng-model of the select element, which in this case is selected - and remove it like so:

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

Updated fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM