的一個問題是,你在呼喚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;
}
};
}]);
這確實不是一個關於角或離子的問題。你是否已經通過函數來跟蹤'circleX'的值? – isherwood
你怎麼能說沒有錯誤?沒有注入$ timeout並且moveLeft不在$ scope中, –
@ Pravat-MujahMaskey如果您嘗試從'ng-mousedown'指令調用未定義的函數,則角度不會產生錯誤。而且因爲'moveLeft'沒有被調用,所以永遠不會調用'$ timeout'。 ;) – plong0