jQuery单击不与AngularJS一起使用的事件

我正在将我的多重php + jquery网站转换为单页角应用程序。 但是我已经用jquery编写了很多代码,所以只打算在路由等方面交换php for angular。

我遇到的一个我无法弄清楚的问题是,在转换停止工作之前,我一直在使用的jquery点击事件。 如果我从控制台调用该函数,那么更改代码以使其从ng-click启动它将起作用。 jquery正在工作,我在提到的函数中放了一些jquery,它运行正常。

            

main.js:

 var mainApp = angular.module('myApp', ['firebase', 'headerPage']); mainApp.directive('headerPage', function(){ return{ restrict: 'E', templateUrl: 'html/header.html' } }); 

header.js

 (function() { var app = angular.module('headerPage', ['firebase']); app.controller("headController", ['$http', '$firebase', '$scope', '$filter', function($http, $firebase, $scope, $filter) { //most of the code } ]); })(); $("#myElement").on("click", function() { console.log("clicked"); }); 

原因是,当您将事件绑定到元素#myElement该元素尚不存在。 由于该元素是作为指令模板的一部分呈现的,因此您需要在指令链接函数中移动绑定处理程序。 好吧,你可以在技术上使用事件委托来解决问题,但这只是黑客的另一个黑客攻击。 最好的办法是在元素上使用ng-click本身(你已经说过你尝试过了)。

尝试使用ng-click而不是https://docs.angularjs.org/api/ng/directive/ngClick

 

然后在控制器内部简单地声明该function

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

我知道这并没有真正解决jQuery的问题,但它有助于将代码保存在一个框架下。

或者:如果你想坚持使用jquery ..你可以使用jquery的事件委托 :

例如:

HTML

  

JS:

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

编辑:添加小提琴fwiw: https ://jsfiddle.net/ge59sbtp/