admin管理员组

文章数量:1431994

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

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

Share Improve this question edited Jun 2, 2015 at 7:20 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jun 2, 2015 at 7:15 Vesko VujovicVesko Vujovic 4001 gold badge7 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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 Remended):

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

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.

本文标签: javascriptHow to attach click event to AngularJS directive with JqueryStack Overflow