-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathangular-flash.js
executable file
·73 lines (62 loc) · 2.21 KB
/
angular-flash.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(function (root, factory) {
if (typeof module !== 'undefined' && module.exports) {
// CommonJS
module.exports = factory(root, require('angular'));
} else if (typeof define === 'function' && define.amd) {
// AMD
define(['angular'], function (react, angular) {
return (root.angularFlash = factory(root, angular));
});
} else {
// Global Variables
root.angularFlash = factory(root, root.angular);
}
}(this, function (window, angular) {
return angular.module('flash', [])
.factory('flash', ['$rootScope', '$timeout', function($rootScope, $timeout) {
var messages = [];
var reset;
var cleanup = function() {
$timeout.cancel(reset);
reset = $timeout(function() { messages = []; });
};
var emit = function() {
$rootScope.$emit('flash:message', messages, cleanup);
};
$rootScope.$on('$locationChangeSuccess', emit);
var asMessage = function(level, text) {
if (!text) {
text = level;
level = 'success';
}
return { level: level, text: text };
};
var asArrayOfMessages = function(level, text) {
if (level instanceof Array) return level.map(function(message) {
return message.text ? message : asMessage(message);
});
return text ? [{ level: level, text: text }] : [asMessage(level)];
};
var flash = function(level, text) {
emit(messages = asArrayOfMessages(level, text));
};
['error', 'warning', 'info', 'success'].forEach(function (level) {
flash[level] = function (text) { flash(level, text); };
});
return flash;
}])
.directive('flashMessages', [function() {
var directive = { restrict: 'EA', replace: true };
directive.template =
'<ol id="flash-messages">' +
'<li ng-repeat="m in messages" class="{{m.level}}">{{m.text}}</li>' +
'</ol>';
directive.controller = ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.$on('flash:message', function(_, messages, done) {
$scope.messages = messages;
done();
});
}];
return directive;
}]);
}));