Skip to content

Instantly share code, notes, and snippets.

@icfantv
Last active March 31, 2016 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icfantv/c3885c32665eeb969f1d67db193be001 to your computer and use it in GitHub Desktop.
Save icfantv/c3885c32665eeb969f1d67db193be001 to your computer and use it in GitHub Desktop.
Alert Service
<!-- this would go in your index.html file, outside ng-view -->
<div class="alerts">
<uib-alert ng-repeat="alert in alerts" type="{{ ::alert.type }}" ng-cloak>{{ ::alert.message }}</uib-alert>
</div>
import _remove from 'lodash/remove';
export class AlertService {
static get $inject() {
return ['$timeout', '$rootScope', 'UuidFactory'];
}
constructor($timeout, $rootScope, UuidFactory) {
this.$timeout = $timeout;
this.$rootScope = $rootScope;
this.UuidFactory = UuidFactory;
this.$rootScope.alerts = [];
}
info(message) {
this.add({
type: 'info',
message,
timeout: 5000
});
}
success(message) {
this.add({
type: 'success',
message,
timeout: 5000
});
}
warn(message) {
this.add({
type: 'warning',
message,
timeout: 7500
});
}
error(message) {
this.add({
type: 'danger',
message,
timeout: 15000
});
}
add(alert) {
const id = this.UuidFactory.uuid();
this.$rootScope.alerts.push({
type: alert.type,
message: alert.message,
id
});
this.$timeout(() => _remove(this.$rootScope.alerts, _alert => _alert.id === id), alert.timeout);
}
}
angular.module('my.app.services', []).service('AlertService', AlertService);
function AlertService($timeout, $rootScope) {
this.info = function(message) {
add({
type: 'info',
message,
timeout: 5000
});
}
this.success = function(message) {
add({
type: 'success',
message,
timeout: 5000
});
}
this.warn = function(message) {
add({
type: 'warning',
message,
timeout: 7500
});
}
this.error = function(message) {
add({
type: 'danger',
message,
timeout: 15000
});
}
function add(alert) {
const id = Math.random();
$rootScope.alerts.push({
type: alert.type,
message: alert.message,
id
});
$timeout(function() {
_remove($rootScope.alerts, function(_alert) {
return _alert.id === id;)
}
},
alert.timeout);
}
}
AlertService.$inject = ['$timeout', '$rootScope', 'UuidFactory'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment