简体   繁体   中英

How to get selected option id in ng-model

I have one select field and am passing selected option value to the client script.

<div>
    <select class="custom-select" multiple id='select-user' ng-model='SelectedOptions'>
        <option ng-repeat='app in data.arr track by $index' value={{app.name}} id={{app.id}}>{{app.name}}</option>
    </select>

    <button ng-click='selectedServers(SelectedOptions)' class='rightBtn'><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
</div>
$scope.selectedServers = function (options) {
    for (i = 0; i < options.length; i++) {
        $scope.datas.push(options[i]);
    }
    console.log($scope.datas)//getting only option value
}

Here I need to get id of selected option as well and push into the array $scope.datas along with option value.

How can I pass the selected option id with value?

Use ng-options with as-for-in syntax:

 angular.module("myApp", []) .controller("myCtrl", function($scope) { $scope.data= [{ name: 'opt1', id: 'id1' }, { name: 'opt2', id: 'id2' }, { name: 'opt3', id: 'id3' }]; $scope.selectedServers = function() { // Here you have the selected options with both name and id console.log($scope.selected); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <select class="custom-select" multiple id='select-user' ng-model="selected" ng-options='s as s.name for s in data'> </select> <button ng-click='selectedServers()' class='rightBtn'><i class="fa fa-arrow-right" aria-hidden="true"></i>Get options</button> </div>

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