要检测 AngularJS 中的点击,我是使用指令还是控制器?

To detect clicks in AngularJS, do I use a directive or a controller?

我想跟踪 abuttoninput[type="submit"]

上的所有点击

我觉得使用附加到 body 标签的控制器很有意义。我需要跟踪每次点击以及每次点击的日期和时间戳。我已经 API 准备好了,但我不知道如何听点击。

我认为控制器是一个很好的方法,但我读过的一些东西是使用指令。基本上把body标签变成指令。

这对我来说真的没有意义,但我是新手。

而且,无论哪种情况,我如何检测点击?我正在尝试使用下面的指令,但它没有触发。说找不到 domElement

这是我的指示。如果我这样做,我不需要控制器来将点击写入我的 API 吗?

'use strict';

var loggerDirectives = angular.module('loggerDirectives', []);

loggerDirectives.directive('loggerdirective', function () {

  return {
    link: function (scope, element, attrs) {

      // Get a reference to the button DOM element
      var clickedDOMElement = document.querySelector(['a, button, input[type="submit"']);

      // Wrap it as a jqLite element
      var clickedItem = angular.element(domElement);

      var onItemClick = function () {
        // Do something
        conlsole.log('Clicked');
      };

      clickedItem.on('click', onItemClick);

      scope.$on('$destroy', function () {
        clickedItem.off('click', onItemClick);
      });
    }
  };
});

将 'listen' 指令添加到您想要收听的所有元素。

var loggerDirectives = angular.module('loggerDirectives', []);

loggerDirectives

.directive('listen', ['listenService', function (listenService) {

  return {
    restrict : 'A',
    link: function (scope, element) {

      element.on('click', function(){
         //Do you stuff here
         listenService.yourFunction();
      });
    }
  };
}]) //You can use your API in a service, here called listenService. It is used in the directive

.service('listenService', function(){
    this.yourFunction = function(){
      //execute your API here
    };
});