从控制器内的Angular指令访问锤子事件信息

时间:2013-09-20 06:02:50

标签: angularjs

我是Angular的新手,我正在尝试使用angular-hammer.js指令获取水龙头的XY坐标。以下是指令的设置方式:

var hmTouchevents = angular.module('hmTouchevents', []),
hmGestures = ['hmHold:hold',
              'hmTap:tap',
              'hmDoubletap:doubletap',
              'hmDrag:drag',
              'hmDragup:dragup',
              'hmDragdown:dragdown',
              'hmDragleft:dragleft',
              'hmDragright:dragright',
              'hmSwipe:swipe',
              'hmSwipeup:swipeup',
              'hmSwipedown:swipedown',
              'hmSwipeleft:swipeleft',
              'hmSwiperight:swiperight',
              'hmTransform:transform',
              'hmRotate:rotate',
              'hmPinch:pinch',
              'hmPinchin:pinchin',
              'hmPinchout:pinchout',
              'hmTouch:touch',
              'hmRelease:release'];

angular.forEach(hmGestures, function(name){
  var directive = name.split(':'),
  directiveName = directive[0],
  eventName = directive[1];
  hmTouchevents.directive(directiveName, ["$parse", function($parse) {
    return {
      scope: true,
      link: function(scope, element, attr) {
        var fn, opts;
        fn = $parse(attr[directiveName]);
        opts = $parse(attr["hmOptions"])(scope, {});
        scope.hammer = scope.hammer || Hammer(element[0], opts);
        return scope.hammer.on(eventName, function(event) {
          return scope.$apply(function() {
            return fn(scope, {
              $event: event
            });
          });
        });
      }
    };
    }
  ]);
});

我的HTML看起来像这样:

<div ng-controller="IndexCtrl" >
    <div class='tap-area' hm-tap="tap();">
    </div>
</div>

我的控制器看起来像这样:

App.controller('IndexCtrl', function ($scope, Myapp) {

$scope.tap = function(ev){
     //How do I get the event.gesture.center.pageX in here?
};

});

2 个答案:

答案 0 :(得分:1)

我想出了如何使这项工作。在return scope.hammer.on(eventName, function(event) {之后我添加了scope.event = event;,然后在我的控制器中,我可以使用this.event.center.pageXthis.event.center.pageY获得点按的XY坐标。

答案 1 :(得分:0)

它是很久以前发布的,但这是另一个解决方案。

只需将$ event添加到您的html