Snowburnt
Snowburnt

Reputation: 6922

Angular directive on div, element has no focus method

I have an angular directive that I'm putting in a div element. In one of my link: functions I call element.focus(). I get a console error: Object [object Object] has no method focus.

I call alert(element the line before and it says element is [[object HTMLDivElement]].

do I need to somehow cast element as a div before calling focus?

This is a directive,

tsUui.directive('userList', function(){
    return{
        restrict: 'A',
                link: function (scope, elem, attrs){
                    scope.something=function() {
                       elem.focus();
                    };
                }
        });

here's a plunkr of most of the project: http://plnkr.co/edit/SiBDuylEv1LUCuWCv5Ep?p=preview

to reproduce error: click one of the user rows, you'll get an alert(elem). if you watch the console you'll see the focus error.

Upvotes: 1

Views: 1003

Answers (2)

Cody Moniz
Cody Moniz

Reputation: 5065

The link function is called prior to the element being rendered, so focus() generally won't work. Here is an example where the "link" attribute on a directive is split into "pre" and "post", for pre-link and post-link functions.

Working Example: http://plnkr.co/edit/Fj59GB

// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
    return {
        link: {
            pre: function preLink(scope, element, attr) {
                console.debug('prelink called');
                // this fails since the element hasn't rendered
                //element[0].focus();
            },
            post: function postLink(scope, element, attr) {
                console.debug('postlink called');
                // this succeeds since the element has been rendered
                element[0].focus();
            }
        }
    }
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />

Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile

Upvotes: 0

tschiela
tschiela

Reputation: 5271

If you load jQuery before AngularJS, Angular uses jQuery insteat of the jqLite(included in AngularJS). Then you can use elem.focus(); Otherwise, as stevuu mentioned, you must use $(elem).focus();

Upvotes: 2

Related Questions