How to control toastr options (or set them globally) from Angular controller or module

27.4k Views Asked by At

Based upon a prior SO article on injecting toastr into your app/controller. I have setup my app.js as follows:

(function () {

   app = angular.module("app", ['breeze.angular']).value('ngToastr', toastr);

    //added toaster as factory so it can be injected into any controller
   angular.module('app').factory('ngNotifier', function (ngToastr) {
       return {
           notify: function (msg) {
               ngToastr.success(msg);
           },
           notifyError: function (msg) {
               ngToastr.error(msg);
           },
           notifyInfo: function (msg) {
               ngToastr.info(msg);
           }
       }
   });

})();

as one of the answers stated I now have access to the toastr control from any controller.

app.controller('reportController', function ($scope, reportLibraryService, ngNotifier,  $log) {
    //report section


    var rvm = this;
    rvm.getReportList = GetReportList;
    rvm.onError = OnError;
    rvm.onReportComplete = OnReportComplete;

    $scope.userId = 1;
    GetReportList($scope.userId);

    function OnReportComplete(response) {
        $scope.reportList = response;
        ngNotifier.notify("Reports Loaded");

    };

    function OnError(reason) {
        $scope.error = "Could not fetch the data.";
        $log.error(reason);
    };

    function GetReportList(userId) {
        $log.info("Getting reports for userid " + userId)
        reportLibraryService.getAllReports($scope.userId).then(rvm.onReportComplete, rvm.onError);
    };
});

The question I have is how do I override the default options? I have tried two approaches so far. First adding an toastr div within the html with the options set, which did not work. And then I tried adding them within the factory but they were ignored there as well.

   angular.module('app').factory('ngNotifier', function (ngToastr) {
       return {
           notify: function (msg) {
               ngToastr.success(msg);
               ngToastr.options = {
                   "closeButton": false,
                   "debug": false,
                   "progressBar": false,
                   "positionClass": "toast-bottom-right",
                   "onclick": null,
                   "showDuration": "300",
                   "hideDuration": "1000",
                   "timeOut": "5000",
                   "extendedTimeOut": "1000",
                   "showEasing": "swing",
                   "hideEasing": "linear",
                   "showMethod": "fadeIn",
                   "hideMethod": "fadeOut"
               }
           }, ...

As a second part to this is toastr the correct tool to use or should I be using angular-toaster instead since this is an angular app? I currently do not have any jQuery dependencies anywhere else in my application.

thanks for any suggestions

4

There are 4 best solutions below

0
On BEST ANSWER

For those trying to override a particular notification, rather than simply override the defaults globally, I was able to do so but with a catch. I wanted to make errors persist (set timeOut to 0) while success messages fade. So for a normal happy-path notification I just use:

toaster.success('Nothing to see here folks', 'Move along');

But for errors I want the message to persist so they can show their manager, write down the error message, whatever. This is easy with the original toastr project, you just pass a JSON object of override options as your last argument such as:

toastr.error('Original toastr example', 'Click to dismiss', {timeOut: 0});

Angularjs-toaster is different, you pass your params to the pop function.

But this did NOT work:

toaster.pop({
           type: 'error',
           title: 'Need More Information',
           body: 'Error 42 occurred, run for the hills!',
           timeOut: 0
           });

I looked in the toaster.js code (I am using version 0.4.15) and it looks like you can pass ordered parameters to pop instead of a JSON object. This DID work:

toaster.pop(
            'error',
            'Need More Information',
            'Error 42 occurred, run for the hills!',
            0 );

Of course I'd prefer to pass an object with named params over a bunch of unlabeled params. I looked at their code closer and saw they changed the case sensitivity from timeOut to timeout!!! This works:

    toaster.pop({
           type: 'error',
           title: 'Need More Information',
           body: 'Error 42 occurred, run for the hills!',
           timeout: 0
           });
0
On

If you have a base angular controller, you can add your site-wide angular.options there. Then, if necessary, you can override the options you want in the toastung controller.

toastr.options = {
  "closeButton": true,
  "debug": false,
  "newestOnTop": false,
  "progressBar": true,
  "positionClass": "toast-top-right",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "5000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};
0
On

Since "AngularJS Toaster" is an AngularJS port of the "toastr" jQuery library, it is definitely better to use it in your AngularJS application.

I use it in similar manner, and didn't have problems setting options in HTML template like this:

<toaster-container toaster-options="{'position-class': 'toast-bottom-right', 'close-button': true, 'body-output-type': 'trustedHtml', 'showDuration': '400', 'hideDuration': '200',}"></toaster-container>
0
On

Just put toastr options in app.config

    app.config(["toastrConfig",function(toastrConfig) {

    var options = {
          "closeButton": true,
          "debug": false,
          "newestOnTop": false,
          "progressBar": true,
          "positionClass": "toast-top-right",
          "preventDuplicates": false,
          "onclick": null,
          "showDuration": "300",
          "hideDuration": "1000",
          "timeOut": "5000",
          "extendedTimeOut": "1000",
          "showEasing": "swing",
          "hideEasing": "linear",
          "showMethod": "fadeIn",
          "hideMethod": "fadeOut"
        };  

        angular.extend(toastrConfig, options);
      })]);