1

Why is it that if I have the following directive it works:

angular.module('app', [])
    .directive('selectOnFocus', function(){
        return{
            restrict: 'A',
            link: function(scope, element){
                element[0].focus(); 
            }
        };
    });

But if I switch it to this, it says element.focus() is not a function. To get this code to work, I need to import jquery in my index.html.

angular.module('app', [])
    .directive('selectOnFocus', function(){
        return{
            restrict: 'A',
            link: function(scope, element){
                element.focus(); 
            }
        };
    });

Here is my HTML:

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
  <script src="app.js"></script>
</head>

<body ng-app="app">
  <div>
    <label>Name:</label>
    <input type="text" ng-model="yourName" placeholder="Enter a name here" select-on-focus >
    <hr>
    <h1>Hello {{yourName}}!</h1>
  </div>
</body>

</html>
1

2 Answers 2

3

I think the question is, why does your code work with element[0].focus(), but not with element.focus(). The answer, as indicated by @mcranston18's comment, is element returns a jqLite object. Refer to the docs for directives here, and jqLite elements here for a deeper understand of what that means. Also, a simple console log of the element object, in the updated jsFiddle, http://jsfiddle.net/rmra3cso/1/, shows what's inside the jqLite object.

In short, when you include jQuery and call element.focus(), you are using the jQuery focus method. When you use element[0].focus(), you are accessing the DOM element itself and using pure JavaScript. I suggest not using jQuery with Angular, and getting used to using jqLite. You'll find you probably won't need jQuery with Angular.

Hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

So to access the direct DOM element its always just element[0]? In what instance would there be more than one item in the element array?
According to the docs, "element is the jqLite-wrapped element that this directive matches." Therefore, in your case, you will always get one jqLite-wrapped element in the link function.
I tried to use element[0].focus() but when running tests I got something like "focus is not a function". But it works like a charm if I use element[0].select(). Do you know why I get this error?
2

That's because focus() is not supported in jqLite and from the angular docs on element

If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.