Vesko Vujovic
Vesko Vujovic

Reputation: 400

How to attach click event to AngularJS directive with Jquery?

I made AngularJS directive, that i load on my home page, also i have JQuery file, where i call alert('it works') when <p> Click </p> element is clicked. Here is the example.

/*
 * This is the directive
 */

outsource.directive('mydirective', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attribute) {
            // Link
        },
        replace: true,
        templateUrl: 'src/app/components/views/directive.html'
    };
});

directive.html file

<p id="clicked"> Click </p>

jquery function

$(document).ready(function() {
    $("#clicked").click(function() {
        alert('it works');
    });
});

This is just a simple question for my real problem. I've notices that angular directive is loaded slower than my function that fires alert message. Because of that i have nothing selected by my selector $("#clicked").

*How i should use angular directive with jquery? What is the right way to solve this jquery-angular issue beside using jqlite? *

Upvotes: 1

Views: 2314

Answers (2)

Tushar
Tushar

Reputation: 87203

Don't use jQuery when you have AngularJS. You can use ng-click of AngularJS to bind click event on elements.

HTML

<p ng-click="clickHandler()">...</p>

JavaScript

In controller

$scope.clickHandler = function() {
    alert('clicked');
};

EDIT

Still you want to use jQuery(Not Recommended):

$(document).on('click', "#clicked", function() {
    alert('it works');
});

Upvotes: 8

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You can use angular ng-click. See this docs.

The ngClick directive allows you to specify custom behavior when an element is clicked.

So why you want to use jQuery? AngularJs provide a best way to handle event for directives, use them.

Upvotes: 0

Related Questions