ng-touchstart and ng-touchend in Angularjs

限于喜欢 提交于 2019-11-30 17:24:55

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>

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

Hope it helps.

The version we came up with uses $parse(), which is what $eval() uses internally. We specifically wanted to handle mousedown and touchstart events using a single directive, but in the angular way so we can include angular style expressions.

Like so:

angular.module("ngStudentselect", []).directive('ngStudentselect', ['$parse', '$timeout', '$rootElement',
function($parse, $timeout, $rootElement) {
    return function(scope, element, attr) {
        var clickHandler = $parse(attr.ngStudentselect);

        element.on('mousedown touchstart', function(event) {
            scope.$apply(function() {
                clickHandler(scope, {$event: event});
            });
        });
    };
}]);

This is a stripped down version of angular's ngClick directive.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!