tesicg
tesicg

Reputation: 4053

How to adapt directive auto-focus to auto-focus="true"/"false"?

I'm not much in Angularjs and use the directive that put focus on particular element. It looks as following:

appModule.directive('autoFocus', function ($timeout) {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            $timeout(function () {
                element[0].focus();
            }, 0);
        }
    };
});

The usage looks as following:

<button auto-focus class="uui-button lime-green btn" ng-click="copyToClipboard()">
    Copy
</button>

I'd like to rearrange directive above to have ability to write: auto-focus="true" or auto-focus="false".

UPDATE:

I've updated code as shown below, but it doesn't work that is the focus is always there regardless I write auto-focus="true" or auto-focus="false".

appModule.directive('autoFocus', function ($timeout) {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            var hasFocus = attrs.autoFocus;
            if (hasFocus) {
                $timeout(function () {
                    element[0].focus();
                }, 0);
            }
        }
    };
});

Upvotes: 0

Views: 265

Answers (1)

Anirudha
Anirudha

Reputation: 32787

You can set the property to true or false and access the value via attrs.autoFocus inside directive's link function

Edit:

appModule.directive('autoFocus', function ($timeout) {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            var hasFocus = attrs.autoFocus;
            if (hasFocus ==="true") {
                $timeout(function () {
                    element[0].focus();
                }, 0);
            }
        }
    };
});

Upvotes: 1

Related Questions