I am trying to implement an automatic alert into my AngularJS application using Angular-Strap and the $alert
service. So far so good, however, I am left with an issue I can't seem to resolve.
Is there a way I can I set a callback to capture when the $alert
is hidden either using the duration
property or the alert.hide()
command? I want to run a function when the alert goes into a hidden state.
My code snippets looks like this:
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');
});
The result of the $promise
, you can pass your own function, eg:
criticalAlert.$promise.then(function(){criticalAlert.hide();console.log('Alert Hidden'); })
More about $promise
anglular $q
UPDATE
You can use $watch
.
Of course, it's not a nice solution, but the best I found. At least, it works!
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);
UPDATED 2
We can use event
of angular.
Live example on 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);
});});
And some important html
<div ng-controller="ExampleController">
<h3>
ExampleController
</h3>
<form name="ExampleForm" id="ExampleForm">
<div id="divForAlert">
</div>
</form>