只使用一次角度指令

Use angular directive only once

本文关键字:一次 指令      更新时间:2023-09-26

嗨,我正在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