【问题标题】:Clear single toastr message清除单个 toastr 消息
【发布时间】:2016-01-12 01:47:50
【问题描述】:

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

toastr.clear([toast]);

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

【问题讨论】:

  • 你可以有关闭按钮。检查配置。
  • 我想以编程方式实现它

标签: angularjs toastr


【解决方案1】:

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

您可以查看Demo

注意- toastr demo page 中显示的 toastr.clear() 示例不是最佳实践,因为它会导致内存泄漏。所有 toast 都存储在 openedToasts 数组中。如果打开 10 个 toast,则数组大小为 10。一段时间后,打开的 toast 将消失,但永远不会清除数组。

因此,如果您以这种方式实现您的 toastr,则必须注意您的数组。如果要从数组中清除一个项目,请确保该项目处于活动状态。

如何清空数组?

要清空数组,我们可以为每个toast注册一个destroy事件:

  $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>

【讨论】:

  • 如果 toastr 中还有一个关闭按钮,我们将如何清除数组或删除数组索引?
猜你喜欢
  • 2017-07-14
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
相关资源
最近更新 更多