1

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? *

2 Answers 2

8

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');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Ok i know how to use ng-click. But what if i have 20 elements where i must trigger alert message? How can i do that? With jquery i just select all elements, and attach event on them.
@VeskoVujovic No. Add ng-click to all of them
0

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.

2 Comments

The answer is, strictly speaking, correct; but talking about quality, Tushar's answer is way above. He says the same thing but explains it and gives an actual answer.
I'm not even convinced this does answer the question. It is more of a comment

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.