Search code examples
javascriptangularjsangularjs-material

Focus on input text after selecting option from selectbox in AngularJS


I'm trying to set focus on input type text after selecting option from selectbox. After selecting option it focus inputs for nano second and then focus again on select box.

Here is a fiddle.

Here is code

    <div ng-controller="MyCtrl" layout layout-align="center center">
        <md-select ng-model="myModel" placeholder="Pick" ng-change="onChange()" md-on-open="onOpen()">
            <md-option value="0">Zero</md-option>
            <md-option value="1">One</md-option>
        </md-select>

        <input type="text" id="fc">
    </div>
<script>
    angular.module('MyApp', ['ngMaterial'])
    .controller('MyCtrl', function ($scope) {
        $scope.onChange = function() {
            document.getElementById('fc').focus();
        };

        $scope.onOpen = function() {
           document.getElementById('fc').focus();
        };
    })
</script>

Solution

  • As it's mentioned in the comments, this is probably an angular-material bug, because it's just working fine if we use a standard select instead. (I think a github issue should be created)

    That said, you can make an uggly workaround to solve it until the bug is fixed: Atttach a directive to manually focus on the input (with a $timeout) when the select is changed.

    Directive: Note the timeout. It needs to be a considerable time... (it works with 250ms):

    .directive('focus', function($timeout) {
       return function(scope, elem, attr) {
          scope.$on(attr.focus, function(e) {
            $timeout(function() {        
              elem[0].focus();         
            }, 250);
          });
       };
    })
    

    Controller: broadcast an event when the select is changed.

    $scope.onChange = function() {
       $scope.$broadcast('selectChanged');
    };
    

    View: Attach the focus directive to your input element:

    <input type="text" id="fc" focus="selectChanged"> 
    

    I've forked your jdsfiddle. Here you can see it working.

    Hope it helps