问题描述
限时送ChatGPT账号..我正在将我的多页 php + jquery 网站转换为单页 angular 应用程序.但是我已经用 jquery 编写了很多代码,所以只打算在路由等方面将 php 换成 angular.
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 to swap the php for angular in regards to the routing etc.
我遇到的一个我无法弄清楚的问题是,在转换停止工作之前,我一直在使用 jquery 单击事件.如果更改代码以使其从 ng-click 中触发,它将起作用,如果我从控制台调用该函数也是如此.jquery 正在工作,我在提到的函数中放入了一些 jquery,它工作正常.
One problem I have come across that I can't figure out is that the jquery click events I have been using up until the convert have stopped working. If change the code to make it fire from an ng-click instead it will work, also if I call the function from the console. jquery is working, I put some jquery inside the mentioned function and it worked fine.
<!doctype html>
<html ng-app="myApp">
<head>
<link href="css/header.css" rel="stylesheet">
<script src="https://ajax.googleapis/ajax/libs/angularjs/1.3.11/angular.js"></script>
<script src="https://cdn.firebase/js/client/2.2.4/firebase.js"></script>
<script src="https://cdn.firebase/libs/angularfire/0.9.2/angularfire.min.js"></script>
<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript' src='js/header.js'></script>
<script type='text/javascript' src='main.js'></script>
</head>
<header-page></header-page>
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
本身(你已经说过你已经尝试过了).
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).
这篇关于jQuery 单击事件不适用于 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论