LoginSignup
8
8

More than 5 years have passed since last update.

AngularJSでフリック検知

Posted at

AngularJSでのフリック検知には、ngTouchというものが使えるようです。
AngularJS: API: ngTouch

導入

まずはライブラリを読み込みます。
今回はGoogleCDNを使います。
バージョン番号のところはAngularJS本体と同じにするといいようです。

index.html
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-touch.js"></script>

読み込み

module関数にパラメータとしてngTouchを指定します。

sample.js
angular.module('sample', ['ngTouch']);

フリックを検知したい要素に適用

画像をフリック可能にする場合なら、こんな感じにng-swipe-leftng-swipe-rightを設定します。

index.html
<body ng-app="sample" ng-controller="SampleController">
  <img ng-src="{{imgsrc}}" ng-swipe-left="swipeLeft()" ng-swipe-right="swipeRight()"/>
</body>

イベント処理

あとはJS側で指定した関数を用意しておけばハンドリングできます。

sample.js
function controller($scope){
  $scope.imgsrc = 'img/hoge.png';
  $scope.swipeLeft = function(){
    $scope.imgsrc = 'img/left.png';
  };
  $scope.swipeRight = function(){
    $scope.imgsrc = 'img/right.png';
  };
}

angular.module('sample').controller('SampleController'['$scope',controller]);

大変ラクチンでありがたいですね。
PCでもクリックしながらヒュッやると一応認識されるみたいです。
今回は1.X系で試してみました。2.X系では試してないです(そもそも2.X系を触ってなry
リファレンスにも無いのが気になるところです。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8