Joined October 2014
·

Sheth

USA
·
·

vvian00 code has a bug. When alert is spliced out of the array, it makes other index values waiting for timeout event to occur, wrong. This is my version of the code.

.factory('AlertService', ['$rootScope', '$timeout', '$sce', function ($rootScope, $timeout, $sce) {
    var exports;
    // create an array of alerts available globally
    $rootScope.alerts = [];
    var alertId = 0; // unique id for each alert. Starts from 0.
    function _factory(alertOptions)
    {
        return $rootScope.alerts.push({
            type: alertOptions.type,
            msg: $sce.trustAsHtml(alertOptions.msg),
            message: alertOptions.msg, // to view the alerts on the console.
            id : alertOptions.alertId,
            timeoutValue: alertOptions.timeoutValue,
            close: function () {
                return exports.closeAlert(this);
            }
        });
    }
    function _addAlert(alertOptions) {
        alertOptions.alertId = alertId++;
        alertOptions.message = alertOptions.msg;
        var that = this;
        this.factory(alertOptions);
        if (alertOptions.timeoutValue > 0) {
            $timeout(function () {
                that.closeAlert(alertOptions.alertId);
            }, alertOptions.timeoutValue);
        }
    }

    function _closeAlert(id) {
        return this.closeAlertByIndex(_.findIndex($rootScope.alerts, function(eachAlert) { return eachAlert.id === id;}));
    }

    function _closeAlertByIndex(index) {
        console.log('closeAlertByIndex  index=' + index + " msg=" + $rootScope.alerts[index].message);
        return $rootScope.alerts.splice(index, 1);
    }

    exports = {
        factory: _factory,
        addAlert: _addAlert,
        closeAlert: _closeAlert,
        closeAlertByIndex: _closeAlertByIndex
    };

    return exports;
}]);

Great work guys. Love it and incorporated vvian00 version.

Achievements
1 Karma
0 Total ProTip Views