jQuery和AngularJS:事件绑定到DOM更改 [英] jQuery and AngularJS: Bind Events to Changing DOM
问题描述
在我的AngularJS DOM,我使用的是NG-包括NG-重复指令内。它加载HTML就好了。无论如何,一个问题我已经是我使用jQuery(最新版本)的几个鼠标结合和在DOM元素与同班那些由NG-重复添加到DOM和鼠标点击事件包括。 JQuery的似乎并不事件处理程序适用于新的DOM另外,虽然。
In my DOM in AngularJS, I am using an ng-include inside a ng-repeat directive. It is loading the HTML just fine. Anyway, an issue I have is that I'm using JQuery (latest version) to bind a few mouse over and mouse click events on elements in the DOM with the same class as those added to the DOM by the ng-repeat and include. JQuery doesn't seem to apply the event handlers to the new DOM addition, though.
在previous版本.live()似乎做我想做的,但它已经在最新版本中被删除。我是否应该清除的元素和绑定重新创建它们每一个在DOM之类的附加元素时添加的?
In previous versions .live() seemed to do what I want, but it has been removed in the latest version. Should I clear the bindings on the elements and re-create them every time the DOM has additional elements of the class added?
推荐答案
答位置:
这是一个多方面的问题。首先,所有的jQuery code事件应该使用$范围。$适用,预期执行angularjs code。例如:
This is a multifaceted question. First of all, all jQuery code events should use $scope.$apply to execute angularjs code as expected. Example:
jQuery(selector).someEvent(function(){
$scope.$apply(function(){
// perform any model changes or method invocations here on angular app.
});
});
在jQuery的最新版本,以有要事基于DOM改变该更新,要1.获取最近的父元素的选择器(前):
In the latest version of jQuery, in order to have events that update based on DOM changes, you want to 1. Get a selector for the nearest parent element (ex):
<div class="myDiv">
<div class="myDynamicDiv">
</div>
<!-- Expect that more "myDynamicDiv" will be added here -->
</div>
在这种情况下,你的父母选择将是.myDiv,和你的孩子选择将.myDynamicDiv。
In this case, your parent selector would be ".myDiv", and your child selector would be .myDynamicDiv.
因此,你要jQuery来对元素的父事件,所以如果子元素改变,它仍然会工作:
Thus, you want jQuery to have the events on the PARENT of the element so if the child elements change, it will still work:
$('.myDiv').on("click", ".myDynamicDiv", function(e){
$(this).slideToggle(500);
$scope.$apply(function(){
$scope.myAngularVariable = !$scope.myAngularVariable;
});
});
注意,$范围。$申请(),以便使jQuery来访问这些角的变量被使用。
Notice that the $scope.$apply() is used in order to enable jQuery to access those angular variables.
希望这有助于!
基督教
Hope this helps! Christian
这篇关于jQuery和AngularJS:事件绑定到DOM更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!