2016-06-21 60 views
0

我们在我们的应用程序中使用了angular-toastr.js。我们已经在我们所有的编辑形式使用以下指令:只显示1个toastr

app.directive('serverError', ['resourceFactory','spinnerService', 'toastr', function (resourceFactory,spinnerService,toastr) { 
 
     return { 
 
      restrict: 'A', 
 
      controller: ['$scope', '$timeout', function ($scope, $timeout) { 
 

 
       var errorToastConfig = {closeButton:true,timeOut:0,tapToDismiss:true}; 
 

 
       $scope.$on('sm:badRequest', function (event, data) { 
 

 
        angular.forEach(data, function (value, key) { 
 
         if (value.message == '') value.message = 'The ' + value.property + ' value is invalid.' 
 
        }); 
 

 
        $scope.errors = data; 
 
        //$scope.alertMessage = resourceFactory.getResource('Messages', 'errorOnForm'); 
 
        //$scope.alertType = 'error'; 
 
        $timeout(function() { 
 
         spinnerService.stopSpinner(); 
 
        }, 0); 
 
        toastr.clear(); 
 
        var errorMsg = ($scope.errors[0] && $scope.errors[0].message?$scope.errors[0].message:resourceFactory.getResource('Messages', 'errorOnForm')); 
 

 
        toastr.error(errorMsg, errorToastConfig); 
 
        $scope.disableAction = false; 
 
       }); 
 

的问题是,当页面遇到错误请求我看到3 toastr信息的画面,而不是仅仅1一上来自我的控制器的代码和来自这个指令的2,因为这个代码被角度执行两次。添加toastr.clear()不能解决问题。理想情况下,如果错误已由控制器的代码处理过,我根本不想运行代码。否则,我想确保我只显示一个包含错误信息的toastr。你看到上面需要改变什么吗?

UPDATE。我也可以显示我们的主要app.js代码来处理错误的请求。当我调试代码时,我可以看到指令代码触发两次,并且执行调用时,toastrs数组为空。

这是应用程序的代码:

app.factory('badRequestInterceptor', ['$rootScope', '$q', function ($rootScope, $q) { 
 
     return { 
 
      'responseError': function (rejection) { 
 
       if (rejection.status === 400) { 
 
        $rootScope.$broadcast("sm:badRequest", rejection.data); 
 
       } 
 
       return $q.reject(rejection); 
 
      } 
 
     }; 
 
    }]); 
 

 
    app.factory('noConnectionInterceptor', ['$rootScope', '$q', function ($rootScope, $q) { 
 
     return { 
 
      
 
      'responseError': function (rejection) { 
 
       console.dir(rejection); 
 
       if (rejection.status === -1) { 
 
        $rootScope.$broadcast("sm:noConnection"); 
 
       } 
 
       return $q.reject(rejection); 
 
      } 
 
     }; 
 
    }]);

回答

1

您可以防止具有由preventDuplicates属性设置为true堆栈相同的祝酒词。

来自文档:基于他们的消息 内容重复匹配到以前的吐司。

只需将属性添加到您的errorToastConfig

var errorToastConfig = {closeButton:true,timeOut:0,tapToDismiss:true, preventDuplicates:true}; 

更多信息请参见docs

+0

不幸的是,虽然它看起来像一个非常有用的属性,但这并不起作用。我认为原因在于烤面包机是在不同的范围内创建的,这就是为什么toastr.clear()或额外的属性没有效果。 app.js具有不良请求的拦截器,就像我刚添加到我的原始邮件一样。当我调试时,我可以看到指令中的代码触发两次,并且toasters数组为空。 – Naomi

+0

我不知道这是否可以帮助,但你有没有尝试过这些其他属性'preventOpenDuplicates'或'maxOpened'? –

+0

我会尝试,但我想我需要弄清楚为什么指令代码会激发两次 - 这是主要关心的问题。可能是我有几种形式的这个指令 - 需要找出答案。 – Naomi