Search code examples
javascriptangularjsdom-eventsjqlite

Angular directives link function


I'm new to Angular. I was trying to learn directives. In my directive's link function I log my element and see that its an array. why it's an array?

<mouse-enter>HI</mouse-enter>

JS:

angular.module('custom.directive').directive('mouseEnter', function () {
    return {
        restrict: 'E',
        link: function (scope, element) {
            console.log(element);// this line prints an array!
            element[0].onmouseover = function () {
                console.log('Mouse Entered!');
            };
        }
    }
});

In which case this array's length can be more than 1!!


Solution

  • Angular's jQlite selectors is an alias of jQuery function when jQuery is available otherwise jQlite will be an Angular's inbuilt small subset of jQuery.

    So jQlite or jQuery selector always returns array.

    https://docs.angularjs.org/api/ng/function/angular.element

    Consider the following DOM structure:

    <div id="test">
        <div class="foo bar" id="dom-element-1">Hello</div>
        <p>ignore me</p>
    </div>
    
    <span class="foo" id="dom-element-2">Hello again</div>
    

    Now when you do either of this: $(".foo") or angular.element(document.querySelectAll(".foo")), you will get a jQlite or jQuery instance which will be an array of two dom elements with IDs dom-element-1 and dom-element-2.