AshD AshD - 7 days ago 7
AngularJS Question

Angular performance when drag drop : various targets and highlighting

I have, listing of many separate items (or tiles) in a list on my page. If the user drags a file over the an item in the list, I conditionally add the highlight class in the onDragEnter and remove the class in the onDragLeave. The highlight class essentially changes the background-color of the item.

Without using a $scope.$apply, the highlight takes a second or so before being reflected in the UI, so I am wrapping the highlight within the $scope.$apply.

Now when I move the file quickly between items, the performance becomes really slow (the highlighting and un-highlighting becomes very slow) due to the large number of digest cycles. Any ideas on how I can improve the performance but at the same time have the changes reflected in the UI pretty quickly.

I tried using $scope.$digest() instead of $scope.$apply but did not notice any improvement in the performance.

My code is:

function onDragEnter() {
$scope.$apply(function() {
$scope.highlight = true; // this controls if the highlight class is added to the item using ng-class
});
}

function onDragLeave() {
$scope.$apply(function() {
$scope.highlight = false;
});
}

Answer

In case this helps someone, using $scope.$evalAsync helped improve the performance significantly.

function onDragEnter() {
    $scope.$evalAsync(function($scope) {
        $scope.highlight = true; // this controls if the highlight class is added to the item using ng-class
    });
}

function onDragLeave() {
    $scope.$evalAsync(function($scope) {
        $scope.highlight = false;
    });
}