Angular-表带警报:alert.hide() 触发时无法捕获

Angular-Strap Alerts: Unable to capture when alert.hide() triggers

我正在尝试使用 Angular-Strap 和 $alert 服务在我的 AngularJS 应用程序中实现自动警报。到目前为止一切顺利,但是,我遇到了一个我似乎无法解决的问题。

有没有一种方法可以设置回调以在使用 duration 属性 或 alert.hide() 命令隐藏 $alert 时捕获?当警报进入隐藏状态时,我想 运行 一个函数。

我的代码片段如下所示:

var alertContent = '';


        // Define the critical alert
        var criticalAlert = $alert({
                            templateUrl: 'templates/critical.alert.tpl.html',  
                            title: ' Critical Alert Detected!', 
                            content: alertContent, 
                            container: 'body', 
                            type: 'danger', 
                            dismissable: false, 
                            duration: '20', 
                            show: false
                        });

...

alertContent = 'Foo Bar!';

...

criticalAlert.$promise.then(criticalAlert.hide);

...

$scope.$on('alert.hide', function() {
            console.log('Alert Hidden');
        });

$promise的结果,可以自己传递函数,eg:

criticalAlert.$promise.then(function(){criticalAlert.hide();console.log('Alert Hidden'); })

更多关于 $promise anglular $q

更新

您可以使用 $watch.

当然,这不是一个很好的解决方案,但却是我找到的最好的解决方案。至少,它有效!

var alert = $alert({
  title: ' Critical Alert Detected!',
  content: 'its Alert!',
  container: 'body',
  type: 'danger',
  dismissable: false,
  duration: '5',
  show: false,
});
$scope.$watch(function(){return alert.$isShown;},function(val){
  if(val===true)
    console.log('alert opened',val);
  else
    console.log('alert closed',val);
});
alert.$promise.then(alert.show);

更新 2

我们可以使用 angular 的 event

jsfiddle.

上的实例
.controller('ExampleController', function($scope, $alert) {
$scope.alert = $alert({
  title: ' Critical Alert Detected!',
  content: 'its Alert!',
  container: '#divForAlert',
  type: 'danger',
  dismissable: false,
  duration: '5',
  show: false,
  prefixEvent:"mymodal",
});
$scope.alert.$promise.then(function() {
  $scope.alert.show();
});
$scope.$root.$on('mymodal.hide.before', function(event) {
  console.log('hide before',event);
});
 $scope.$root.$on('mymodal.hide', function(alert) {
  console.log('hide',alert);
});});

还有一些重要html

<div ng-controller="ExampleController">
<h3>
  ExampleController
</h3>
<form name="ExampleForm" id="ExampleForm">
  <div id="divForAlert">

  </div>
</form>