Search code examples
javascripthtmlangularjsangularjs-select

Not able to select previously selected option


ng-change is not getting fired after selection of previously selected option. Because of which I am not able to handle the same next selection.

<select ng-model="selectedOption" ng-change="handleSelection()">                        
    <option value="A" selected>A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
</select>

I want to show to the user the last selected option and want to handle the same. But since ng-model is not changing on next same option selection ng-change is not getting fired.

How to handle this scenario?


Solution

  • You can do without ng-change by only checking click count:

    1st click event raises after each opening select

    2nd click event raises after one item selected

    we use blur event to clear click count after lost focus

    by this way you will get selected item without change event and without selecting new item :

    <select ng-model="selectedOption" ng-click="handleSelection()" ng-blur="resetClickCount()">                        
        <option value="A" selected>A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>
    

    --

    app.controller("myCtrl", function($scope) {
        $scope.clickCount = 0;
    
        $scope.handleSelection = function() {
            $scope.clickCount++;
            if ($scope.clickCount==2) {
                alert($scope.selectedOption);
                $scope.clickCount = 0;
            }
        }
    
        $scope.resetClickCount = function() {
            $scope.clickCount = 0;
        }
    });