segunda-feira, 25 de julho de 2016

SweetAlert com AngularJS


     O SweetAlert é uma biblioteca para exibir alertas mais estilizados para os usuários. Para usar é necessário baixar o arquivo CSS e JavaScript do endereço https://github.com/oitozero/ngSweetAlert.

     Criamos uma função para preparar as mensagens no arquivo do controller principal, podendo até colocar um time para que elas fechem automaticamente após um intervalo de tempo determinado.

/* Create the sweetAlert Service singleton */
function sweetAlertService() {
    this.success = function(message) {
        swal('', message, 'success');
    };
    this.warningT = function(message) {
        swal({
           title : ' ',
           text : message,
           type : "warning",
           timer : 3000
        });
    };
    this.successT = function(message) {
       swal({
          title : ' ',
          text : message,
          type : "success",
          timer : 3000
       });
    };
    this.error = function(message) {
       swal('', message, 'error');
    };
    this.warning = function(message) {
       swal('', message, 'warning');
    };
    this.info = function(message) {
       swal('', message, 'info');
    };
    this.custom = function(configObject) {
       swal(configObject);
    }
}

      Colocamos as dependências no modulo e no controller. No app coloca-se da seguinte forma:

/* Criar aplicação no angularjs. */
angular.module('meuApp',[]);

/* Criar o serviço do SweetAlert */
angular.module('meuApp').service('sweetAlertService', sweetAlertService);

     A injeção no controller fica assim:

(function() {

 angular.module('meuApp').controller('meuController', meuController);

     meuController.$inject = [ '$scope', 'sweetAlertService' ];
function meuController($scope, sweetAlertService) {
   ...
       var _self = this;
     //aqui de acordo com a minha lógica posso chamar a função e passar a mensagem que será exibida para o usuário com o SweetAlert.

   sweetAlertService.warning(“sua mensagem aqui”);
   sweetAlertService.success(“sua mensagem aqui”);

   //Como definimos as mensagens que tem o timer com T no final podemos chamá-las da mesma forma:
   sweetAlertService.warningT(“sua mensagem aqui”);
   sweetAlertService.successT(“sua mensagem aqui”);
       ...
     }
})();

É sempre bom dar uma olhada na documentação, mas o uso é bem simples. Abraços.

Nenhum comentário:

Postar um comentário