Angular-Strap警报:当alert.hide()触发

时间:2016-02-05 05:20:43

标签: angularjs alert angular-strap

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

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

我的代码片段如下所示:

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');
        });

1 个答案:

答案 0 :(得分:0)

$promise的结果,您可以传递自己的函数,例如:

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

我们可以使用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>