我正在尝试使用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');
});
答案 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>