0

Once jQuery is included in Angular, inside directives one is free to use both $(element) and $(this) for DOM manipulations.

What is the difference between them? Is one recommended over the other? Are they interchangeable?

iConnor
  • 19,153
  • 13
  • 57
  • 91
Sangram Singh
  • 6,991
  • 15
  • 47
  • 76

2 Answers2

3

$(this) will depend on the context of the method being executed, $(element) will always refer to the the directive is attached to.

here's a contrived example

module.directive('myDirective', [function() {
    return {
        template: '<div><button id="btn">Click Me</button></div>',
        restrict: 'E',
        link: function(scope, element, attrs, controller) {
                $("#btn").on('click', function() {
                    // $(this) != $(element)
                    // $(this) is the button element from the template
                    // $(element) is the directive element
                });
            }
        }
}]);
TheHippo
  • 54,987
  • 13
  • 72
  • 98
Jason
  • 15,640
  • 3
  • 46
  • 70
1

Since angular js is using jqlite(a minimal version of jquery)under the hoods for selectors,it may be the same in angular js also with different name.

Refer: AngularJS DOM selector

Community
  • 1
  • 1
webcoder
  • 656
  • 6
  • 12
  • Intersting answer to know more about this keyword in JavaScript: http://stackoverflow.com/questions/3127429/javascript-this-keyword – webcoder Oct 07 '13 at 15:11