Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear single toastr message

I would like to clear/hide a single toastr message among multiple toastr messages displayed at a time. Is there any workaround for that rather than clearing the entire/multiple toastr messages simultaneously. I have tried the following code, but doesn't worked for me.

toastr.clear([toast]);

Ref:https://github.com/Foxandxss/angular-toastr

like image 580
ABHILASH SB Avatar asked Oct 19 '22 00:10

ABHILASH SB


1 Answers

You can only clear the active toastr, not an already dismissed toastr.

For example:

var openedToast = null;

$scope.openToast = function(){      
  openedToast  = toastr['success']('message 2', 'Title 2');
  toastr['success']('this will be automatically dismissed', 'Another Toast');      
}
//if you click clearToast quickly, it will be cleared. 
$scope.clearToast = function(){
  if(openedToast )
    toastr.clear(openedToast);
   openedToast = null; //you have to clear your local variable where you stored your toast otherwise this will be a memory leak!
}

You can check the Demo

Note - The toastr.clear() example shown in the toastr demo page is not the best practice, as it will cause a memory leak. All toasts are stored in the openedToasts array. If you open 10 toasts, the array size will be 10. After a while, the opened toasts will be gone, but the array will never be cleared.

Thus, if you implement your toastr this way, you have to take care your array. If you want to clear an item from the array, make sure that item is active.

How we can clear the array?

To clear the array, we can register a destroy event for each toast:

  $scope.openedToasts = [];       
  $scope.openToast = function() {
    var toast = toastr['success']('message 1', 'Title 1');
    $scope.openedToasts.push(toast);

    registerDestroy(toast); //we can register destroy to clear the array
  }

  function registerDestroy(toast) {
    toast.scope.$on('$destroy', function(item) {
      $scope.openedToasts = $scope.openedToasts.filter(function(item) {
        return item.toastId !== toast.toastId;
      });
    });
  }

In HTML you can check the length :

<span>array length: {{openedToasts.length}} </span>
like image 127
Tasnim Reza Avatar answered Nov 22 '22 14:11

Tasnim Reza