Neena Vivek Neena Vivek - 3 months ago 9
AngularJS Question

Unable to move an element using AngularJS

This is my markup:

<button class="left" ng-mousedown="moveLeft()">Left</button>


This is my code:

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);
};
});


There are no errors in the console. Why is the variable
circleX
not changing? I have never used Angular before so I might have made a silly mistake.

Answer

One problem is that you are calling mouseLeft(), but that function is not exposed on $scope.

Another problem is that you never assign anything to leftTimer.

Another problem is that you don't inject $timeout.

I would try something like:

<button class="left" ng-mousedown="mousePress()" ng-mouseup="mouseRelease()">Left</button>

and

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);
    };
}]);