Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change cursor to wait while the angular $apply is running

I have a complicated page with a lot of nested ng-repeat. The $apply function can take several seconds. During that time the browser is hung and the user cannot do anything.

As a courtesy I would like to change the mouse pointer to hourglass while $apply is running. How can I do that?

like image 840
John Henckel Avatar asked Nov 03 '16 20:11

John Henckel


2 Answers

The trick is to change the cursor (using addClass), then invoke the slow code with a timeout at the end of which you change the cursor back to normal.

JSFiddle

    var mybody = angular.element(document).find('body');
    mybody.addClass('waiting');   // set cursor to hourglass
    setTimeout(function() {
        doSlowStuff();
        $scope.$apply();
        mybody.removeClass('waiting');  // set cursor to normal
    }, 0);

You have to do the slow stuff in a timeout so that the addClass will be applied before the slow stuff starts.

The CSS is just

.waiting { cursor: wait; }
like image 152
John Henckel Avatar answered Nov 10 '22 14:11

John Henckel


Use the ng-class directive to set classes and ng-disabled to disable buttons:

<div ng-app="myApp" ng-controller="MyCtrl"
     ng-class="{waiting: status=='running'}">
    Hello, {{name}}!
    <button ng-click="more();" ng-disabled="status=='running'">
    CLICK HERE
    </button> {{status}}

Use the $timeout service which is integrated with the AngularJS digest cycle:

$scope.more = function() {
    //var mybody = angular.element(document).find('body');
    //mybody.addClass('waiting');
    $scope.status = 'running';
    //setTimeout(function() {
    $timeout(function() {
        doSlowStuff();
        $scope.status = 'done';
        //$scope.$apply();
        //mybody.removeClass('waiting');
    }, 1000);
};

The DEMO on JSFiddle

like image 43
georgeawg Avatar answered Nov 10 '22 13:11

georgeawg