这是我的标记:
<button class="left" ng-mousedown="moveLeft()">Left</button>
这是我的代码:
angular.module('ionicApp', ['ionic'])
.controller("wallControl", function($scope) {
var leftTimer;
$scope.mousePress = function() {
moveLeft();
};
var moveLeft = function() {
if (circleX > 0) {
circleX -= 4;
}
leftInterval = $timeout(moveLeft, 1000);
};
$scope.mouseRelease = function() {
$timeout.cancel(leftTimer);
};
});
控制台中没有错误。为什么变量circleX
没有变化?我之前从未使用过Angular,所以我可能犯了一个愚蠢的错误。
答案 0 :(得分:1)
一个问题是您正在调用mouseLeft()
,但该功能未在$scope
上公开。
另一个问题是你从未向leftTimer
分配任何内容。
另一个问题是你没有注射$timeout
。
我会尝试类似的事情:
<button class="left" ng-mousedown="mousePress()" ng-mouseup="mouseRelease()">Left</button>
和
angular.module('ionicApp', ['ionic'])
// notice the DI syntax (which is not only a best practice, but is necessary if you minify your code)
// notice $interval service is injected
.controller("wallControl", ['$scope', '$interval', function($scope, $interval) {
// used to store the $interval handle so it can be cancelled
var leftTimer;
$scope.mousePress = function() {
// start running moveLeft every 1000ms
leftTimer = $interval(moveLeft, 1000);
};
var moveLeft = function() {
if (circleX > 0) {
circleX -= 4;
}
// no need to call itself on $timeout - $interval doing that
};
$scope.mouseRelease = function() {
// stop the moveLeft interval
$interval.cancel(leftTimer);
};
}]);
更新:多方向
非常直接,对代码进行了一些小改动。我更进了一步,详细阐述了其他几个概念,使代码更加真实。
<button class="left" ng-mousedown="startMoveX(-1)" ng-mouseup="stopMoveX()">Left</button>
<button class="right" ng-mousedown="startMoveX(1)" ng-mouseup="stopMoveX()">Right</button>
和
angular.module('ionicApp', ['ionic'])
.controller("wallControl", ['$scope', '$interval', function($scope, $interval) {
// some settings (magic numbers are bad m'kay)
var xSpeed = 4;
var xBounds = { min: 0, max: 1000 };
// circleX need to be defined somewhere
// how you will use it for drawing is another story
var circleX = (xBounds.min + xBounds.max) / 2.0;
// x-motion variables
var xMoveTimer;
var xDirection;
// starts the x-motion
$scope.startMoveX = function(direction) {
// track which direction to move (used as multiplier on speed)
xDirection = direction;
// make sure the xMoveTimer is not already running
if(!xMoveTimer){
// start running moveX every 1000ms
xMoveTimer = $interval(moveX, 1000);
}
};
// stops the x-motion
$scope.stopMoveX = function() {
if(xMoveTimer){
// stop it
$interval.cancel(xMoveTimer);
// release it
xMoveTimer = undefined;
}
};
// performs the x-motion
var moveX = function() {
// move it move it
circleX += xSpeed * xDirection;
// lock it to bounds
if(circleX < xBounds.min){
circleX = xBounds.min;
}
else if(circleX > xBounds.max){
circleX = xBounds.max;
}
};
}]);
答案 1 :(得分:0)
由于您试图将事件绑定到函数并且$scope
不知道该函数,因此它无法工作。您需要将该函数添加到$scope
,即$scope.moveLeft = (){ ... }
将ng-mousedown
绑定更改为您已声明的范围函数$scope.mousepress() { ... }