仅使用角度指令一次

时间:2016-03-23 08:36:31

标签: javascript html angularjs angularjs-directive

您好我正在使用body标签上的指令来捕获全局事件,例如mousedown,mouseup,scroll等。我想知道是否有一种可能的方法只允许使用一个角度指令一次(类似于单例概念)或者如果指令只能由某个html标签使用(在我的情况下是body标签)。

指令:

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>

3 个答案:

答案 0 :(得分:4)

如何在

运行时实现此功能
angular.module('app.helper', []).run(['$rootElement', function (root) {

    root.on('mousedown'...
}]);

答案 1 :(得分:1)

检查名称是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
        });
      }
    }
  }]);

答案 2 :(得分:1)

如果您仍想在指令内部进行检查,只有在您执行此操作后才能运行:

您可以将您的指令设置为命名函数,然后向其添加一个参数,就像它是一个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;

编辑:不使用命名函数

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