AngularJs动态事件处理,而无需使用指令 [英] AngularJs dynamic Event handler without using directive
问题描述
<机身NG控制器=myController的>
< mydirective>< / mydirective>
< /身体GT;
有没有AngularJS任何附加动态事件,而无需使用指令标签,因为它可能需要在HTML中添加额外的标记。
<!DOCTYPE HTML>
< HTML NG-应用=APPNAME>
< HEAD>
&所述; SCRIPT SRC =http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js>&下; /脚本>
< /头><机身NG控制器=myController的>
< mydirective>< / mydirective>
< /身体GT;<脚本>VAR应用= angular.module('APPNAME',[]);
app.controller('myController的',函数($范围){});
app.directive('mydirective',函数(){
返回{
限制:'E',
链接:功能(范围,ELEM,ATTRS){
angular.element(文件).bind(鼠标按下',函数(){
的console.log('点击文件');
});
}
}
});< / SCRIPT>< / HTML>
当然可以。看看下面的jsfiddle。
但是,永远永远记得要解除事件为好,否则可能导致内存泄漏和其他有害的情况。
VAR buttonElement = angular.element('#则myButton');
buttonElement.bind('点击',功能(E){
警报('这是一个code绑定事件');
});
此外,使用指令,如NG-点击,NG-鼠标悬停始终是建议,因为这些发达和开发商成千上万的良好测试。这将帮助您开发强大的应用程序
的jsfiddle:通过code &LT绑定事件;<更新基于OP的评论小提琴
<body ng-controller="MyController">
<mydirective></mydirective>
</body>
Is there any way in AngularJS to attach dynamic event without using directive tag because it may need to add additional tag in html.
<!DOCTYPE html>
<html ng-app="appname">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<mydirective></mydirective>
</body>
<script>
var app = angular.module('appname', []);
app.controller('MyController', function($scope){
});
app.directive('mydirective', function(){
return {
restrict: 'E',
link: function(scope, elem, attrs){
angular.element(document).bind('mousedown', function(){
console.log('clicked on document');
});
}
}
});
</script>
</html>
Sure you can. Take a look at the following JSFiddle. However, always and always remember to unbind events as well, otherwise it might lead to memory leaks and other unwanted scenarios.
var buttonElement = angular.element('#myButton');
buttonElement.bind('click', function (e) {
alert('This is a code bound event');
});
Also, using directives such as 'ng-click', ng-mouseover' is always advised, since these are well-developed and well-tested by thousands and thousands of developers. It will help you to develop robust applications
JSFiddle: Bind events through code << Updated the fiddle based on OP's comments
这篇关于AngularJs动态事件处理,而无需使用指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!