我想在一次显示的多个 toastr 消息中清除/隐藏单个 toastr 消息。是否有任何解决方法,而不是同时清除整个/多个 toastr 消息。我尝试了以下代码,但对我不起作用。
toastr.clear([toast]);
Run Code Online (Sandbox Code Playgroud)
您只能清除活动的 toastr toastr,而不能清除已解雇的 toastr。
例如:
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!
}
Run Code Online (Sandbox Code Playgroud)
您可以查看演示
注意 - toastr 演示页面toastr.clear()中显示的示例
不是最佳实践,因为它会导致内存泄漏。所有的 toast 都存储在数组中。如果打开10个toast,数组大小将为10。一段时间后,打开的toast就会消失,但数组永远不会被清除。openedToasts
因此,如果你以这种方式实现你的 toastr,你必须照顾你的数组。如果要从数组中清除某个项目,请确保该项目处于活动状态。
我们如何清除数组呢?
要清除数组,我们可以为每个 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;
});
});
}
Run Code Online (Sandbox Code Playgroud)
在 HTML 中,您可以检查长度:
<span>array length: {{openedToasts.length}} </span>
Run Code Online (Sandbox Code Playgroud)