Search code examples
javascriptangularjsdependency-injectiontoastr

Inject/use Angular Service in Toastr.js


I've recently started using the Toastr.js library to display alerts on an angular website. I use an Angular service to connect to the database and pull or post alerts, then send the resulting alerts to the toastr service, which works perfectly. I want to customize the library so that when a user clicks the close icon on a toast, the toastr service will send an update to the database. I have the relevant code in place in my customized toastr.js, but I don't know how to use the pre-existing Angular service to make this call.

How can I inject/reference/use the pre-existing Angular service into toastr.js so I can use it's methods to post to the database? It doesn't use Angular, and is wrapped in require syntax.

For reference, toastr.js looks something like the below:

(function (define) {
    define(['jquery'], function ($) {
        return (function () {
            //code stuff here, functions
        });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) { //Node
        module.exports = factory(require('jquery'));
    } else {
        window.toastr = factory(window.jQuery);
    }
}));

Solution

  • Use angular-toastr Plugin.

    app.controller('foo', function($scope, toastr) {
      toastr.info('We are open today from 10 to 22', 'Information');
    });
    

    Below is how you can edit the Configuration of toastr and customise

    app.config(function(toastrConfig) {
      angular.extend(toastrConfig, {
        allowHtml: false,
        closeButton: false,
        closeHtml: '<button>&times;</button>',
        extendedTimeOut: 1000,
        iconClasses: {
          error: 'toast-error',
          info: 'toast-info',
          success: 'toast-success',
          warning: 'toast-warning'
        },  
        messageClass: 'toast-message',
        onHidden: null,
        onShown: null,
        onTap: null,
        progressBar: false,
        tapToDismiss: true,
        templates: {
          toast: 'directives/toast/toast.html',
          progressbar: 'directives/progressbar/progressbar.html'
        },
        timeOut: 5000,
        titleClass: 'toast-title',
        toastClass: 'toast'
      });
    });
    

    Toast with custom HTML

    toastr.info('<input type="checkbox" checked> Success!', 'With HTML', {
      allowHtml: true
    });