jQuery click events not working with AngularJS

前端 未结 3 1039
醉酒成梦
醉酒成梦 2020-12-21 17:50

I am in the process of converting my multipaged php + jquery website into a single page angular app. However I have written a lot of code with jquery already so only intend

相关标签:
3条回答
  • 2020-12-21 18:16

    alternatively: if you want to stick with jquery ..you may be able to make use of jquery's event delegation :

    for example:

    HTML

    <div id="parent">
      <a href="#" class="child">Click Here</a>
    </div>
    

    JS:

    $('#parent').on('click', '.child', function() {
      console.log("click");
    });
    

    EDIT: added fiddle fwiw: https://jsfiddle.net/ge59sbtp/

    0 讨论(0)
  • 2020-12-21 18:23

    The reason is because, when you bind the event to the element #myElement the element does not exist yet. Since that element is being rendered as a part of the directive template you would need to move the bind handler inside the directive link function. Well, you could technically use event delegation to solve the issue but it is just another hack upon hack. Best bet would be to use ng-click itself on the element (Which you already said you have tried out).

    0 讨论(0)
  • 2020-12-21 18:34

    Try using ng-click instead https://docs.angularjs.org/api/ng/directive/ngClick

    <div id="myElement" ng-click="myFunction()"></div>
    

    Then inside your controller simply declare the function

    myApp.controller('MyController', ['$scope', function($scope) {
      $scope.myFunction = function() {
        //Content here
      }
    }]);
    

    I know this doesn't really resolve the issue with jQuery but it helps to keep code all under one framework.

    0 讨论(0)
提交回复
热议问题