Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-touchstart and ng-touchend in Angularjs

I have an element which fires functions on ng-mousedown and ng-mouseup. However, It doesn't work on touch screen, is there any directive like ng-touchstart and ng-touchend?

like image 583
ciembor Avatar asked Oct 02 '14 21:10

ciembor


2 Answers

There is a module for this: https://docs.angularjs.org/api/ngTouch

But you can write your own directives for events too:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
    </head>
    <body ng-app="plunker">
        <div  ng-controller="MainCtrl">
            <div my-touchstart="touchStart()" my-touchend="touchEnd()">
                <span data-ng-hide="touched">Touch Me ;)</span>
                <span data-ng-show="touched">M-m-m</span>
            </div>
        </div>
        <script>
            var app = angular.module('plunker', []);
            app.controller('MainCtrl', ['$scope', function($scope) {
                $scope.touched = false;

                $scope.touchStart = function() {
                    $scope.touched = true;
                }

                $scope.touchEnd = function() {
                    $scope.touched = false;
                }
            }]).directive('myTouchstart', [function() {
                return function(scope, element, attr) {

                    element.on('touchstart', function(event) {
                        scope.$apply(function() { 
                            scope.$eval(attr.myTouchstart); 
                        });
                    });
                };
            }]).directive('myTouchend', [function() {
                return function(scope, element, attr) {

                    element.on('touchend', function(event) {
                        scope.$apply(function() { 
                            scope.$eval(attr.myTouchend); 
                        });
                    });
                };
            }]);
        </script>
    </body>
</html>
like image 160
Kostya Shkryob Avatar answered Oct 05 '22 17:10

Kostya Shkryob


I have made those ealier today since I needed it myself:

  • ngTouch (a collection of the below)
  • ngTouchmove
  • ngTouchstart
  • ngTouchend

Hope it helps.

like image 21
Mark Topper Avatar answered Oct 05 '22 15:10

Mark Topper