Search code examples
javascriptangularjsng-options

Finding ngOption selected within ngRepeat


I have a table which is populated with directive ngRepeat, and within each item is ngOptions. On change I call function transactionListFilter in the controller to find out which select has changed, so I can then reset all other select to default value 'Multiple'.

View

<tr data-ng-repeat="item in $ctrl.tableData">
    <td>
        <select 
         data-ng-options="item.appAndType for item in item.serviceUIs" 
         data-ng-model="selectedItem" 
         data-ng-change="$ctrl.transactionListFilter(selectedItem)" >
         <option value="">Multiple</option>
        </select>
    </td>                                    
</tr>

Controller

function transactionListFilter(data) {
    console.log(data)
    $scope.filter = data;
};      

So it should look like this:

enter image description here

But if I select the second select, the first select stll is populated with an application number, rather than resetting to 'Multiple'. When I submit ngModel value, it submits the data form the ngOptions.

enter image description here

Question

How do I identify the selected select from the controller, so I can reset all other select value to 'Multiple'?


Solution

  • One approach is to make the selection a property of the ng-repeat iterator:

    <tr data-ng-repeat="item in $ctrl.tableData">
        <td>
            <select data-ng-options="ui.appAndType for ui in item.serviceUIs" 
                    data-ng-model="item.selectedUi" 
                    data-ng-change="$ctrl.transactionListFilter(item,$index)" >
               <option value="">Multiple</option>
            </select>
        </td>                                    
    </tr>
    
    function transactionListFilter(item, index) {
        $ctrl.tableData.forEach( (_ , idx) => {
             if (index != idx) {
                 _.selectedUi = null;
             };
        });  
        console.log(item.selectedUi, index)
    };