AngularJS Bootstrap alert dismiss-on-timeout attribute doesn't work

后端 未结 5 1681
春和景丽
春和景丽 2021-01-04 13:28

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 regular

5条回答
  •  心在旅途
    2021-01-04 13:47

    My proposal would be to wrap it in a alertFactory that can be used from everywhere:

    App.factory('alertFactory',['$rootScope', 
        function($rootScope) {
        var alertService = {};
        $rootScope.alerts = [];
    
        // will automatidally close
        // types are success, warning, info, danger
        alertService.addAuto = function(type, msg, delay) {
            var alert = {'type': type, 'msg': msg};
            $rootScope.alerts.push(alert);      
            if (!delay ) {
                delay = 2500; // default delay is 2500ms
            }  
            window.setTimeout(function() {
                var index = $rootScope.alerts.indexOf(alert);
                if (index > -1) {
                    $rootScope.alerts.splice(index, 1);
                    $rootScope.$apply(); // refresh GUI
                } 
            }, delay);
        }
    
        return alertService;
    }])
    

    Place this, e.g. in your `index.html

    
    ...
    {{alert.msg}}
    

    Call like

    App.controller('myCtrl', [ "alertFactory", function(alertFactory) {
    
        var optionalDelay = 2500;
        alertFactory.addAuto('success', 'my alert text', optionalDelay);
    }]);
    

提交回复
热议问题