angularjs没有touch时间需要添加directive
插件代码如下
"use strict"; angular.module("ngTouch", []) .directive("ngTouchstart", function () { return { controller: function ($scope, $element, $attrs) { $element.bind('touchstart', onTouchStart); function onTouchStart(event) { var method = $element.attr('ng-touchstart'); $scope.$event = event; $scope.$apply(method); }; } }; }).directive("ngTouchmove", function () { return { controller: function ($scope, $element, $attrs) { $element.bind('touchstart', onTouchStart); function onTouchStart(event) { event.preventDefault(); $element.bind('touchmove', onTouchMove); $element.bind('touchend', onTouchEnd); }; function onTouchMove(event) { var method = $element.attr('ng-touchmove'); $scope.$event = event; $scope.$apply(method); }; function onTouchEnd(event) { event.preventDefault(); $element.unbind('touchmove', onTouchMove); $element.unbind('touchend', onTouchEnd); }; } }; }).directive("ngTouchend", function () { return { controller: function ($scope, $element, $attrs) { $element.bind('touchend', onTouchEnd); function onTouchEnd(event) { var method = $element.attr('ng-touchend'); $scope.$event = event; $scope.$apply(method); }; } }; });
html代码如下:
<script type="text/javascript" src="../../js/angular.min-1.4.3.js"></script> <script type="text/javascript" src="../../js/ngTouch.js" ></script> <script type="text/javascript"> var app=angular.module("app",["ngTouch"]); app.controller("touchCtrl",function($scope){ $scope.touchStart=function(){ alert("touchStart"); } $scope.touchMove=function(){ console.log("touchMove"); } $scope.touchEnd=function(){ alert("touchEnd"); } }); </script> </head> <body> <div ng-controller="touchCtrl"> <button ng-touchstart="touchStart()">touchStart</button> <button ng-touchmove="touchMove()">touchMove</button> <button ng-touchend="touchEnd()">touchEnd</button> </div> </body>
当然如果用到其中一个事件,可以直接使用在controller上面
例如(代码可能有问题仅做参考):
app.controller("touchCtrl",function($scope){ $scope.touchStart=function(){ alert("touchStart"); } $scope.touchMove=function(){ console.log("touchMove"); } $scope.touchEnd=function(){ alert("touchEnd"); } }).directive("ngTouchstart", function () { return { controller: function ($scope, $element, $attrs) { $element.bind('touchstart', onTouchStart); function onTouchStart(event) { var method = $element.attr('ng-touchstart'); $scope.$event = event; $scope.$apply(method); }; } }; })
代码仅做参考,场景需要自己调试