0

I am using the angular modal service and I am trying to implement some keypress functionality for a smooth UX.

<button type="button" autofocus ng-click="close('Yes')" class="btn btn-primary" data-dismiss="modal">Yes</button>

The problem is that when the modal pops up, it doesn't have focus. Focus remains on the button clicked to activate the modal.

Is there some way to reset autofocus without reloading the page? Or is there some way to grab focus when the modal activates, but have it do so each time the modal opens?

I tried implementing the focus service as described in the answer to this post, but I couldn't get it to work with the modal.

Here is a plunker that demonstrates the behavior: Plunker

Community
  • 1
  • 1
tpie
  • 6,021
  • 3
  • 22
  • 41

1 Answers1

0

Here is the working demo: Plunker

I ended up finding this example: Programmatically Setting Focus

It accomplishes it with a directive on whatever element you want to get focus:

app.directive('syncFocusWith', function($timeout, $rootScope) {
        return {
            restrict: 'A',
            scope: {
                focusValue: "=syncFocusWith"
            },
            link: function($scope, $element, attrs) {
                $scope.$watch("focusValue", function(currentValue, previousValue) {
                    if (currentValue === true && !previousValue) {
                        $element[0].focus();
                    } else if (currentValue === false && previousValue) {
                        $element[0].blur();
                    }
                })
            }
        }
    });

Getting it to work for my modal was easy. I just added this little timeout function to the modal's controller, giving it a half a second to display the modal before trying to set the focus:

$timeout(function() {
  $scope.isFocused = true;
},500)

and this attribute on the element we want to get focus:

 sync-focus-with="isFocused" 
tpie
  • 6,021
  • 3
  • 22
  • 41