angularjs – 清除单个toastr消息

前端之家收集整理的这篇文章主要介绍了angularjs – 清除单个toastr消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在一次显示的多个toastr消息中清除/隐藏单个toastr消息.是否有任何解决方法,而不是同时清除整个/多个toastr消息.我尝试了以下代码,但对我没用.

toastr.clear([toast]);

编号:https://github.com/Foxandxss/angular-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!
}

你可以查看Demo

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

因此,如果以这种方式实现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>

猜你在找的Angularjs相关文章