Angular:从 js 添加 ngClick [英] Angular: Add ngClick from js
本文介绍了Angular:从 js 添加 ngClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Angular 为移动设备开发小型网页.我想像
一样为整个页面切换点击监听器$('.page').on('click',...);$('.page').off('click',...);
但是以 Angular 的方式.而且我不想在某些条件下使用 ng-Click
,因为大多数时候点击应该不起作用,它只是用于错误处理.是否可能或者我需要使用纯 js/jQuery?
面板 HTML:
<div class="alert-text">{{ errorMessage }}</div>
解决方案
我创建了一个指令:
- 它应该与
ngIf
结合使用. ngIf
应该引用作用域上的可赋值变量- 例如不要这样做:
ng-if='myFunc()'
或ng-if='var1 ||var2'
这里是一个plunker:http://plnkr.co/edit/fmNH2PbRrruRqGFYiui1?p=preview
指令:
app.directive('errorBox', function($document, $parse){返回 {链接:功能(范围,榆树,属性){var clickHandler = function(){范围.$应用(函数(){$parse(attrs.ngIf).assign(scope.$parent,'')})$document.off('click', clickHandler);};$document.on('click', clickHandler)}}});
html:
<div class="alert-text">{{ errorMessage }}</div>
I am developing small web page for mobile devices with Angular. I want to toggle click listener for whole page like
$('.page').on('click',...);
$('.page').off('click',...);
but in Angular way. And I don't want to use ng-Click
with some conditions because most of the time the click should not work, it is just for error handling. Is it possible or I need to user pure js/jQuery?
Panel HTML:
<div class="alert error" ng-show="errorMessage">
<div class="alert-text">{{ errorMessage }}</div>
</div>
解决方案
I created a directive:
- It should be used in conjunction with
ngIf
. ngIf
should refer to an assignable variable on the scope- For example don't do this:
ng-if='myFunc()'
orng-if='var1 || var2'
here is a plunker: http://plnkr.co/edit/fmNH2PbRrruRqGFYiui1?p=preview
Directive:
app.directive('errorBox', function($document, $parse){
return {
link: function(scope,elm,attrs) {
var clickHandler = function(){
scope.$apply(function(){
$parse(attrs.ngIf).assign(scope.$parent,'')
})
$document.off('click', clickHandler);
};
$document.on('click', clickHandler)
}
}
});
html:
<div ng-if="errorMessage" error-box class="alert error">
<div class="alert-text">{{ errorMessage }}</div>
</div>
这篇关于Angular:从 js 添加 ngClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文