5

我想在一次显示的多个 toastr 消息中清除/隐藏单个 toastr 消息。是否有任何解决方法,而不是同时清除整个/多个 toastr 消息。我尝试了以下代码,但对我不起作用。

toastr.clear([toast]);

参考:https ://github.com/Foxandxss/angular-toastr

4

1 回答 1

3

您只能清除活动的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!
}

您可以查看演示

注意 - 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;
      });
    });
  }

在 HTML 中,您可以检查长度:

<span>array length: {{openedToasts.length}} </span>
于 2015-10-14T09:43:56.080 回答