ng-options model not updated when use arrow keyboard instead of mouse

All we need is an easy explanation of the problem, so here it is.

I Created js fiddle: Fiddle

I create a form with some ng-options in it, and it have strange behavior when you use the button instead of mouse (just click on the textbox and press “tab” and you can select it using arrow key).

<form ng-controller="MyApp" id="Apps" name="Apps" ng-submit="SendApp()" role="form" novalidate>
    <input type="text" name="title" ng-model="Info.Title" />
    <select id="Formula" ng-model ="Info.Genre" ng-change= "ChangeGenre()"
                        ng-options="id as name for (id, name) in Genre" blank></select>
     <select class="form-control" ng-model ="Info.Program" 
                        ng-options="Program as Name for (Program, Name) in Program" ng-change="ChangeProgram()" blank></select>
    <h3>{{Info.Genre}}</h3>
    <h3>{{Info.Program}}</h3>
    <button type=submit>Submit this </button>
</form>

Javascript:

var theApp = angular.module("TheApp", []);

theApp.controller("MyApp", ['$scope', function($scope){
    $scope.Program = {"1":"Music","2":"Theater","3":"Comedy"};

    $scope.Genre = {"1":"Mystery", "2":"Thriller", "3":"Romance"};

    $scope.ChangeProgram = function(){
        alert($scope.Info.Program + " " + $scope.Info.Genre);
    }
    $scope.ChangeGenre = function (){
        console.log($scope.Info.Genre);

    }
    $scope.SendApp = function(){
        alert($scope.Info.Program + " " + $scope.Info.Genre);
    }
}]);

The ng-model are not updated when you select the first options on First try.

What’s Wrong, and How To Fix this?

Update:

As Mentioned on comment below, To reproduce, enter mouse into textfield, tab to combobox and try to select the second option (Thriller) using keyboard. This will fail on the first attempt, once the third or first option is selected, the second option is also recognized.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Using the the directive proposed here, this works for me:

theApp.directive("select", function() {
    return {
      restrict: "E",
      require: "?ngModel",
      scope: false,
      link: function (scope, element, attrs, ngModel) {
        if (!ngModel) {
          return;
        }
        element.bind("keyup", function() {
          element.triggerHandler("change");
        })
      }
   }
})

I forked the fiddle.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply