Using Jquery inside AngularJS directive good or bad idea?

All we need is an easy explanation of the problem, so here it is.

Below you can see my code for the directive.

My question is: ” Can i use jquery with directives? Is that a good idea? If not why? “

outsource.directive('dedicated', function(){

        return {
           restrict: 'E',
           link: function(scope, element, attribute){

                 $("#klik").click(function(){
                    alert('works');
                 });

           },

           replace: true,
           templateUrl: 'src/app/components/views/dedicated-prices.html'
        };
    });

P.s this code works.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should not be using jquery as Angular itself has a lighter version for it known as jqlite.

More documentation on JQLITE

So your directive should look like:

outsource.directive('dedicated', function(){

    return {
       restrict: 'E',
       link: function(scope, element, attribute){

             var elem = angular.element(document.querySelector('#klik'))
             angular.element(elem).triggerHandler('click');

       },

       replace: true,
       templateUrl: 'src/app/components/views/dedicated-prices.html'
    };
});

Method 2

Simple Answer: YES (Simply refer jquery.js above Angular.js in HTML page. jqLite will be replaced by jQuery)

You would be using jQuery for DOM manipulation & there are many discussions going on this topic (whether to use or not in modern browsers).


One of the popular posts in the recentdays: http://lea.verou.me/2015/04/jquery-considered-harmful/

Despite everything, jQuery is still a very popular, highly used DOM library. And, it works with many modern UI frameworks seamlessly.

Method 3

Interesting question. I’ve got some jquery with element selection in some directives/controllers in my codebase.

I always feel dirty using it and only do it when I really need to, unfortunately it’s almost always a time bomb and leads to me cursing myself a few months down the line and refactoring to use a more angulary method.

Have one last look to see if there’s a native angular way of doing what you’re trying to do, you won’t regret it!

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply