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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With