Skip to content

Instantly share code, notes, and snippets.

@toymachiner62
Last active August 29, 2015 14:11
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 toymachiner62/8baea854a78ce28108bd to your computer and use it in GitHub Desktop.
Save toymachiner62/8baea854a78ce28108bd to your computer and use it in GitHub Desktop.
Angular Messages Service
// Some controller
// ON PAGE LOAD
// If there is an existing success message, show it
if(Messages.getSuccess()) {
success(Messages.getSuccess());
}
// If there is an existing error message, show it
if(Messages.getError()) {
error(Messages.getError());
}
/*--------- Message Helpers ---------*/
// Helper method to easily add a success message
var modalSuccess = function(message) {
$scope.modalError = null;
$scope.modalSuccess = message;
};
// Helper method to easily add an error message
var modalError = function(message) {
$scope.modalSuccess = null;
$scope.modalError = message;
};
// Helper method to easily add a success message
var success = function(message) {
$scope.error = null;
$scope.success = message;
};
// Helper method to easily add an error message
var error = function(message) {
$scope.success = null;
$scope.error = message;
};
// Clears all the success and error messages
var clear = function() {
$scope.error = null;
$scope.success = null;
$scope.modalError = null;
$scope.modalSuccess = null;
};
$scope.$on('success', function() {
success(Messages.getSuccess());
});
$scope.$on('error', function() {
error(Messages.getError());
});
<!-- Error message -->
<div class="alert alert-danger" ng-show="error">
<i class="icon-remove-sign"></i>
{{error}}
</div>
<!-- Success message -->
<div class="alert alert-success" ng-show="success">
<i class="icon-ok-sign"></i>
{{success}}
</div>
angular.module('myApp').factory('Messages', function($rootScope) {
var success = null;
var error = null;
return {
getSuccess: function() {
return success;
},
setSuccess: function(message) {
success = message;
$rootScope.$broadcast('success');
},
getError: function() {
return error;
},
setError: function(message) {
error = message;
$rootScope.$broadcast('error');
},
clear: function() {
success = null;
error = null;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment