ng-touch
Wscats opened this issue · 1 comments
Wscats commented
引入文件
anguar的单页面页面引入两个脚本,一个angular的框架,一个是触摸的库
<script type="text/javascript" src="dist/js/angular.js"></script>
<script type="text/javascript" src="dist/js/angular-touch.js"></script>
记得在这里引入ngTouch模块
var app = angular.module('wsscat', ['ngRoute','ngTouch']);
编写路由
.when('/touch', {
controller: 'touchCtrl',
templateUrl: 'view/touch.html'
})
还要在controller里面把注入$swipe服务,如果我们打印$swipe服务会发现里面只暴露了一个方法bind
touchCtrl控制器
执行$swipe服务的bind方法,bind方法可以传入三个参数
function(element, eventHandlers, pointerTypes)
第一个是获取的节点,可以是directive link方法中获取的element,也可以是原生JS选择器获取的节点,然后放进angular.element函数里面,第二参数是需要监听的触摸动作,总共四个start,move,end和cancel,可以在他们对应的函数中获取对应滑动所在的坐标点
app.controller('touchCtrl', ['$scope', '$swipe', function($scope, $swipe) {
console.log($swipe);
var ele = angular.element(document.getElementById('trapezoid'));
console.log(ele);
$swipe.bind(ele, {
'start': function(coords) {
startX = coords.x;
startY = coords.y;
console.log(coords);
},
'move': function(coords) {
//console.log(coords);
var delta = coords.x - startX;
if(delta < -300 && !locked) {
console.log('trun right');
} else if(delta > 300 && !locked) {
console.log('trun left');
}
},
'end': function(coords) {
console.log(coords);
},
'cancel': function(coords) {
console.log(coords);
}
});
}])
touch视图
<div id="trapezoid"></div>
在控制器中可以有两个事件监听左右滑动(上下滑动却没有)
$scope.left = function(){
console.log('wsscat is left');
}
$scope.right = function(){
console.log('wsscat is right');
}
<p ng-swipe-left="left()" ng-swipe-right="right()">尝试左右滑动</p>
Wscats commented
自定义的手势插件
app.directive('ngWs', function() {
return {
link: function(scope, ele, attr) {
var xStart, xEnd, yStart, yEnd;
function direction(xStart, xEnd, yStart, yEnd) {
console.log("xStart:" + xStart + "xEnd:" + xEnd + "yStart:" + yStart + "yEnd:" + yEnd);
if(Math.abs(xStart - xEnd) >= Math.abs(yStart - yEnd)) {
if(xStart >= xEnd) {
console.log("left")
scope.$apply(attr.ngWs)
} else {
scope.$apply(attr.ngWs)
//scope.$apply(scope.touch())
}
} else {
if(yStart >= yEnd) {
console.log("up")
scope.$apply(scope.touch())
} else {
console.log("down")
scope.$apply(scope.touch())
}
}
}
ele.bind('touchstart', function(e) {
xStart = e.targetTouches[0].pageX;
yStart = e.targetTouches[0].pageY;
})
ele.bind('touchend', function(e) {
xEnd = e.changedTouches[0].pageX;
yEnd = e.changedTouches[0].pageY;
direction(xStart, xEnd, yStart, yEnd)
})
}
}
})