1

我想跟踪一个a,buttoninput[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);
      });
    }
  };
});
4

1 回答 1

2

将“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
    };
});
于 2015-10-18T20:48:22.353 回答