Skip to content Skip to sidebar Skip to footer

How Can I Focus A Button After Its Been Enabled?

I have an html button like so: The button is initially disabled so the autofoc

Solution 1:

As it was mentioned in the comment a directive would be good for this. The following will watch the model and passed to it and focus on the element when it becomes true.

module.directive('focusToMe', function($parse) {
    return {
        restrict: 'A',
        compile: function() {
            var directiveName = this.name;

            returnfunction(scope, element, attrs) {
                scope.$watch(attrs[directiveName], function(newVal, oldVal) {
                    if (newVal) {
                        element.focus();
                    }
                })
            }
        }
    }
});

You would then add it to your button element:

<button autofocus role="button" ng-disabled="something.$invalid" focus-to-me="something.$invalid">{{ Continue }}</button>

Solution 2:

The following directive controls the focus of an element to which it is applied:

.directive('focusOn', function() {
    returnfunction(scope, elem, attrs) {
        scope.$watch(function(scope) {
            return scope[attrs.focusOn];
        },
        function(val) {
            if (val) {
                elem[0].focus();
            }
        });
    };
});

Apply it to the button element like:

<button focus-on="focusMe">click-me</button>

See full example in this plunk: http://plnkr.co/edit/zrd9hl7ilTrhIKshStXR?p=preview

Solution 3:

Ah I got it working. I had to set the focus function to fire off after one cycle of the event loop with $timeout like so:

.directive('focusToMe', function($timeout) {
        return {
            restrict: 'A',
            compile: function() {
                var directiveName = this.name;

                returnfunction(scope, elem, attrs) {
                    scope.$watch(attrs[directiveName], function(newVal, oldVal) {
                        if (newVal) {
                            $timeout(function() {
                                elem[0].focus();
                            }, 0)
                        }
                    })
                }
            }
        }
    })

Post a Comment for "How Can I Focus A Button After Its Been Enabled?"