touch – 如何在Angular.js中使用hammer.js

我是新的Angular.js和阅读我知道角没有像tap,双击等事件我正试图结合Hammer.js没有成功.

代码gist

/**
 * angular-hammer.js
 * Inspired by AngularJS' implementation of "click dblclick mousedown..." 
 *
 * This ties in the Hammer events to attributes like:
 * 
 *   hm-tap="add_something()"
 *   hm-swipe="remove_something()"
 *
 * and also has support for Hammer options with:
 *
 *  hm-tap-opts="{hold: false}"
 *
 * or any other of the "hm-event" listed underneath.
 */
angular.forEach('hmTap:tap hmDoubletap:doubletap hmHold:hold hmTransformstart:transformstart hmTransform:transform hmTransforend:transformend hmDragstart:dragstart hmDrag:drag hmDragend:dragend hmSwipe:swipe hmRelease:release'.split(' '), function(name) {
  var directive = name.split(':');
  var directiveName = directive[0];
  var eventName = directive[1];
  angular.module('MYMODULE').directive(directiveName, 
  ['$parse', function($parse) {
    return function(scope, element, attr) {
      var fn = $parse(attr[directiveName]);
      var opts = $parse(attr[directiveName + 'Opts'])(scope, {});
      element.hammer(opts).bind(eventName, function(event) {
        scope.$apply(function() {
          console.log("Doing stuff", event);
          fn(scope, {$event: event});
        });
      });
    };
  }]);
});

现在我已经添加到我的html文件

<!--...-->
<script src="/js/jquery-1.9.0.js"></script>
    <script src="/js/angular.js"></script>

    <script src="/js/hammer.js"></script>
    <script src="/js/jquery.hammer.js"></script>
    <script src="/js/angular-hammer.js"></script>

    <script src="/js/app/controllers.js"></script>
</html>

但是当我尝试在我的html中使用它不工作.

我试过了

<li hmTap="click($event)">...</li>
<li ngTap="click($event)">...</li>
<li hm-tap="click($event)">...</li>
<li ng-tap="click($event)">...</li>

没有人能工作,可以帮我这个麻烦吗?

最佳答案
给一个去

将hammer.js和jquery.hammer.js添加到您的解决方案中.使用JQuery和Angular.

这样的事情

<script src="js/jquery/jquery.min.js"></script>
<script src="js/hammer/hammer.js"></script>
<script src="js/hammer/jquery.hammer.js"></script>
<script src="js/angular/angular.min.js"></script>

Then use Angular directives to define new HTML attributes.

在这个例子中,我创建一个名为on-tap的新属性

angular.module('myApp.directives', [])
       .directive('onTap', function () {
         return function (scope, element, attrs) {
           return $(element).hammer({
             prevent_default: false,
             drag_vertical: false
           })
             .bind("tap", function (ev) {
               return scope.$apply(attrs['onTap']);
             });
         };
       });

然后,您可以为每个Hammer事件创建一个指令:

按住,点按,doubletap,transformstart,transform,transformend,dragstart,drag,dragend,release,swipe.

你的HTML将会如下所示:

<button on-tap="DoAngularMethod()">Tap me</button>

转载注明原文:touch – 如何在Angular.js中使用hammer.js - 代码日志