Skip to content

Instantly share code, notes, and snippets.

@jpcercal
Last active October 21, 2016 16:57
Show Gist options
  • Save jpcercal/0d4d43a64ebf5ab734899a980fd23e8d to your computer and use it in GitHub Desktop.
Save jpcercal/0d4d43a64ebf5ab734899a980fd23e8d to your computer and use it in GitHub Desktop.
A angular service to use the sweetalert library.
(function () {
'use strict';
angular
.module('yourApp')
.factory('SweetAlert', SweetAlert);
/* @ngInject */
function SweetAlert($http, $interpolate, $rootScope) {
/**
* Constructor method.
*
* @return {SweetAlert}
*/
return function () {
/**
* Default options.
*
* @type {Object}
*/
var opt = {
type: "",
html: true,
showCancelButton: false,
showLoaderOnConfirm: false,
closeOnConfirm: false,
title: "",
text: "",
confirmButtonText: "Confirmar",
confirmButtonColor: "#DD6B55",
cancelButtonText: "Cancelar"
};
/**
* The url of an existant template.
*
* @type {string}
*/
var templateUrl;
/**
* Store the scope.
*
* @type {Object}
*/
var currentScope;
/**
* Given an url, make a GET HTTP request.
*
* @param {string} url
* @return {$q} a promise
*/
var loadTemplateFromUrl = function (url) {
return $http.get(url);
};
/**
* Create a new scope.
*
* @return {Object}
*/
var createNewScope = function () {
return $rootScope.$new();
};
/**
* Make a interpolation in a string.
*
* @param {string} template
* @return {string}
*/
var interpolateTemplate = function (template) {
if (!currentScope) {
currentScope = createNewScope();
}
return $interpolate(template)(currentScope);
};
/**
* Set the scope.
*
* @param {Object} value
* @return {SweetAlert}
*/
this.scope = function (value) {
currentScope = value;
return this;
};
/**
* Replace or add key/value to the default options.
*
* @param {Object} value
* @return {SweetAlert}
*/
this.options = function (value) {
angular.extend(opt, value);
return this;
};
/**
* Set the title of an alert.
*
* @param {string} value
* @return {SweetAlert}
*/
this.title = function (value) {
opt.title = value;
return this;
};
/**
* Set the url that will be used to fill the text property as a html.
*
* @param {string} value
* @return {SweetAlert}
*/
this.template = function (value) {
templateUrl = value;
return this;
};
/**
* Set the text property directly.
*
* @param {string} value
* @return {SweetAlert}
*/
this.text = function (value) {
opt.text = value;
return this;
};
/**
* Build an alert.
*
* @param {Function} callback
*/
this.build = function (callback) {
var render = function () {
opt.text = interpolateTemplate(opt.text);
return typeof callback === 'undefined' ? swal(opt) : swal(opt, callback);
};
if (templateUrl) {
loadTemplateFromUrl(templateUrl).success(function (response) {
opt.text = response;
render();
});
return;
}
render();
};
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment