angularJS移动应用触摸touch事件

首先我们定义一个指定(directive),如下面代码:

.directive('myTouchEven', ['$swipe', "$rootScope", function ($swipe, $rootScope) {
    return {
        restrict: 'EA',
        link: function (scope, ele, attrs, ctrl) {
            var startX, pointY;
            $swipe.bind(ele, {
                'start': function (coords) {
                    startX = coords.x;
                    pointY = coords.y;
                    c("startX:" + startX + "pointY:" + pointY)
                },
                'move': function (coords) {
                    var a = coords.x - startX;
                    if (a < -100 && a > -110) {
                        startX = coords.x;
                        $rootScope.$broadcast("TouchEven", "back");
                    } else if (a > 100 && a < 110) {
                        startX = coords.x;
                        $rootScope.$broadcast("TouchEven", "next");
                    }
                    c("move:" + a + " coords.x:" + coords.x)

                },
                'end': function (coords) {
                    c("end")
                    c("endX:" + coords.x + "endY:" + coords.y)
                },
                'cancel': function (coords) {
                    c("cancel")
                }
            });
        }
    }
}])

这里使用$swipe来帮顶触摸事件,在start事件中记录开始点击的坐标值(x、y)的数据;然后我们监控move事件,计算当前的坐标值(x、y)于开始点击的坐标值相差是多少,如果大于或者小于我们设定的数值,那么则发送一个全局广播,这里注入了$rootScope,用来发送全局广播($broadcast),其他指令(directive)、服务(service)、控制器(controller)等只要注册了(TouchEven)广播监听,就能接收到我们发送的广播事件,下面是示例代码:

.controller("ListController", function ($scope, $routeParams,ajax) {
    $scope.pages = 1;

    $scope.$on("TouchEven",function(a,b){
        var is_send = null;
        if(is_send == null){
            is_send = 1;

            if(b == "back"){
                $scope.pages -= 1;
            }else if(b == "next"){
                $scope.pages += 1;
            }

            ajax.get("/api/v1/articleList",{pages:$scope.pages})
                .success(function(data){
                    is_send = null;
                    c(data)
                    /**
                     * write something code.
                     */

                })
                .error(function(err){
                    is_send = null;
                    toast(err.response_err)
                    /**
                     * write something code.
                     */
                })


        }


    });
    
})

 

 

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |