【发布时间】:2014-10-02 21:35:30
【问题描述】:
我有一个在ng-mousedown 和ng-mouseup 上触发函数的元素。但是,它在触摸屏上不起作用,有没有像ng-touchstart和ng-touchend这样的指令?
【问题讨论】:
标签: javascript angularjs mousedown mouseup touchstart
我有一个在ng-mousedown 和ng-mouseup 上触发函数的元素。但是,它在触摸屏上不起作用,有没有像ng-touchstart和ng-touchend这样的指令?
【问题讨论】:
标签: javascript angularjs mousedown mouseup touchstart
有一个模块:https://docs.angularjs.org/api/ngTouch
但您也可以为事件编写自己的指令:
<!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>
【讨论】:
【讨论】:
touchstart 事件的坐标,然后在touchmove 上,我将根据新事件检查坐标。
我们提出的版本使用 $parse(),这是 $eval() 内部使用的。我们特别想使用单个指令来处理 mousedown 和 touchstart 事件,但是以角度方式,因此我们可以包含角度样式表达式。
像这样:
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});
});
});
};
}]);
这是 Angular 的 ngClick 指令的精简版。
【讨论】: