只使用一次角度指令
Use angular directive only once
嗨,我正在body标记上使用一个指令来捕获全局事件,如mousedown、mouseup、scroll等。
指令:
angular.module('app.helper', [])
.directive('globalEvents', ['$document', function($document) {
return function(scope, element, attrs) {
element.bind('mousedown', function(e) {
// some action
});
$document.bind('scroll', function(e) {
// some action
});
}
}]);
视图:
<body global-events>
...<div global-events></div><- is it possible to disallow this or any other usage of the directive
</body>
像一样在运行时实现这一点怎么样
angular.module('app.helper', []).run(['$rootElement', function (root) {
root.on('mousedown'...
}]);
检查名称是否为body
:
angular.module('app.helper', [])
.directive('globalEvents', ['$document', function($document) {
return function(scope, element, attrs) {
if (element[0].localName === 'body') {
element.bind('mousedown', function(e) {
// some action
});
$document.bind('scroll', function(e) {
// some action
});
}
}
}]);
如果你仍然想在指令内部进行检查,只运行一次,你可以这样做:
您可以将指令设置为命名函数,然后将参数添加到其中,就好像它是一个javascript对象一样(事实上是这样)。这样,您就可以保存一个变量,告诉您指令是否已经运行过一次,它可以用于任何标记,甚至是不同于正文的标记,并确保仅为该标记注册事件
angular.module('app.helper', []).directive('globalEvents', ['$document', globalEvents]);
function globalEvents($document) {
return function(scope, element, attrs) {
if(globalEvents.first){
element.bind('mousedown', function(e) {
// some action
});
$document.bind('scroll', function(e) {
// some action
});
globalEvents.first = false;
}
}
}
globalEvents.first = true;
EDIT:不使用命名函数
angular.module('app.helper', [])
.directive('globalEvents', ['$document', function($document) {
var first = true;
return function(scope, element, attrs) {
if(first){
element.bind('mousedown', function(e) {
// some action
});
$document.bind('scroll', function(e) {
// some action
});
console.log("first");
first = false;
} else {
console.log("second");
}
}
}]);
查看此plunkr:http://plnkr.co/edit/sdK9Mcme19EtnQAw1zOq?p=preview
相关文章:
- Javascript返回值只在循环中返回一次
- Jquery FadeIn FadeOut 只工作一次
- Javascript html每点击一次就会更改url
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- 一次显示一个隐藏指令-AngularJS
- 一次显示一个指令AngularJS
- Angular.js指令格式化程序只调用过一次,或者如何告诉ngModel表现得像watchCollection
- 就绪函数上的指令只能执行一次
- Angular指令删除只调用一次的DOM元素
- 只使用一次角度指令
- 为什么将 ng-select 替换为自定义指令会导致$http请求不会每隔一段时间发送一次
- AngularJS指令在ng-repeat中为每个项目设置不同的值,只重复一次
- Angular JS-需要与页面上的所有指令进行通信,这些指令来自只运行一次的服务中的代码
- 如何从Angular指令运行一次jQuery插件
- 为什么这个角度指令只调用一次
- AngularJS指令-如何让一个事件只触发一次,否则它'将在多个元素上触发
- {{警报更新.currentPage}} in指令在angular-route中每修改一次路由
- AngularJS指令只被调用一次
- 当与ngIf指令组合时,一次绑定重新计算变量是否正确?-AngularJS
- Ng-repeat和指令一次展开一个列表项