I'm trying to use AngularJS Bootstrap alerts like explained here with the "dismiss-on-timeout" attribute. It has no effect in this example, the alert just appears regularly and doesn't disappear.
<alert type="warning" dismiss-on-timeout="2000">Alert text</alert>
It does however work in the ng-repeat example from the site:
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)" dismiss-on-timeout="2000">{{alert.msg}}</alert>
Is the problem the missing close attribute? If so, how do you write a close function for an alert that's not part of an array?
Closing Alerts To close the alert message, add a . alert-dismissible class to the alert container. Then add class="close" and data-dismiss="alert" to a link or a button element (when you click on this the alert box will disappear).
Bootstrap Alerts are used to provide an easy way to create predefined alert messages. Alert adds a style to your messages to make it more appealing to the users. There are four classes that are used within <div> element for alerts. .alert-success.
Well it works, it's just dismissOnTimeout
directive invokes close
method of the alert directive controller. This controller in its turn uses outer scope close
method. So you need to implement it with so that directive could call it:
<alert type="danger" close="closeAlert()" ng-if="show"
dismiss-on-timeout="2000">Something happened.</alert>
and in controller:
$scope.show = true;
$scope.closeAlert = function(index) {
$scope.show = false;
};
Actually, you do not need to use the variable ($scope.show = false;
) to hide the alert(s). All you need to do is to make sure that the array that holds the alerts can only have one item at a time, unless you want multiple/previous alerts showing on the screen. Just delete the alert after showing it. See below:
Markup
<uib-alert ng-repeat="alert in alerts" dismiss-on-timeout="2000" type="{{alert.type}}" close="closeAlert()">{{alert.msg}}</uib-alert>
Controller
//array to hold the alerts to be displayed on the page
$scope.alerts = [];
/**
*This function is used to push alerts onto the alerts array.
*/
$scope.addAlert = function(type, message) {
//add the new alert into the array of alerts to be displayed.
$scope.alerts.push({type: type, msg: message});
};
/**
*This function closes the alert
*/
$scope.closeAlert = function(index) {
//remove the alert from the array to avoid showing previous alerts
$scope.alerts.splice(0);
};
So when you want to display an alert:
$scope.addAlert('success', 'My message');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With