Coder Social home page Coder Social logo

angular-toastr's Introduction

Angular Toastr

This project needs new maintainers. I cannot maintain it anymore, I don't do more AngularJS and I don't have the time for it anymore, please send an email or open an issue if you wish to maintain it

Code Climate Build Status devDependency Status

NOTE: For angular 1.2.x support check angular-1.2 branch or download the 0.4.x release of angular-toastr.

angular-toastr was originally a port of CodeSeven/toastr. It could now show some differences with it.

The goal is to provide the same API than the original one but without jQuery and using all the angular power.

Demo

Demo

Installation

Use npm:

$ npm install angular-toastr

If you are not using npm (you should), you can use bower:

$ bower install angular-toastr

To use a CDN, you can include one of these options:

<script src="https://unpkg.com/angular-toastr/dist/angular-toastr.tpls.js"></script>
<link rel="stylesheet" href="https://unpkg.com/angular-toastr/dist/angular-toastr.css" />
<!-- or -->
<script src="https://cdn.jsdelivr.net/npm/angular-toastr@2/dist/angular-toastr.tpls.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/angular-toastr@2/dist/angular-toastr.css">

Or you can grab the latest release and add both the css and javascript file:

<link rel="stylesheet" type="text/css" href="angular-toastr.css" />
<script type="text/javascript" src="angular-toastr.tpls.js"></script>

Note: If you add a script tag for angular-toastr, keep in mind that you need the tpls version or the other depending if you want the default template or not (see below).

If you want animations, don't forget to add angular-animate.

Then add toastr to your modules dependencies:

angular.module('app', ['ngAnimate', 'toastr'])

Usage

Toastr usage is very simple, by default it comes with four types of notification messages:

Success:

app.controller('foo', function($scope, toastr) {
  toastr.success('Hello world!', 'Toastr fun!');
});

Success Image

Info:

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

Info Image

Error:

app.controller('foo', function($scope, toastr) {
  toastr.error('Your credentials are gone', 'Error');
});

Error Image

Warning:

app.controller('foo', function($scope, toastr) {
  toastr.warning('Your computer is about to explode!', 'Warning');
});

Warning Image

Apart from that you can customize your basic toasts:

No title:

app.controller('foo', function($scope, toastr) {
  toastr.success('I don\'t need a title to live');
});

No Title

Closing toasts programmatically:

app.controller('foo', function($scope, toastr) {
  toastr.clear([toast]);
});

If no toast is passed in, all toasts will be closed.

Getting active (open) toasts:

app.controller('foo', function($scope, toastr) {
  toastr.active();
});

Refreshing an opened toast:

app.controller('foo', function($scope, toastr) {
  var toast = toastr.error('You are not allowed to do this!');
  // after doing something...
  toastr.refreshTimer(toast, 5000);
});

The second parameter is optional and will fallback to the configured timeOut.

It return the number of active toasts in screen.

Other options

A toast has a isOpened flag to see whether it is opened or not.

Toastr customization

This library has two parts, a container and the toasts you put in it.

To configure the container you need to modify the toastrConfig, for example:

app.config(function(toastrConfig) {
  angular.extend(toastrConfig, {
    autoDismiss: false,
    containerId: 'toast-container',
    maxOpened: 0,    
    newestOnTop: true,
    positionClass: 'toast-top-right',
    preventDuplicates: false,
    preventOpenDuplicates: false,
    target: 'body'
  });
});

Those are the default values, you can pick what you need from it and override with your values.

  • autoDismiss If set, show only the most recent maxOpened toast(s)
  • containerId: The name of the container where you want to append your toasts (the container will be created for you).
  • maxOpened: Maximum number of toasts displayed at once.
  • newestOnTop: Add new toasts on top of the old one. Put on false to put them on the bottom.
  • positionClass: The position where the toasts are added.
  • preventDuplicates: Prevent duplicates of the last toast.
  • preventOpenDuplicates: Prevent duplicates of open toasts.
  • target: The element to put the toastr container.

To customize a toast you have two options. First, you can set a default option to be applied globally to all toasts in the same way you modified the container:

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'
  });
});
  • allowHtml: Your toast can use custom HTML here (See Issue 3)
  • closeButton: Whether to display an "X" close button on the toast.
  • closeHtml: Html element to be used as a close button.
  • extendedTimeOut: The timeout after you hover a toast.
  • extraData: If you override the template, you can pass global extra data to your toasts.
  • iconClasses: The default type classes for the different toasts.
  • messageClass: The class for the toast's message.
  • progressBar: A progress bar to see the timeout in real time.
  • tapToDismiss: Whether the toast should be dismissed when it is clicked.
  • templates: To override the default path of the templates.
  • timeOut: The timeout before the toasts disappear.
  • titleClass: The class for the toast's title.
  • toastClass: Base class for toasts.

Toasts have 3 different callbacks:

  • onHidden: A callback function called when a toast gets hidden.
    • First parameter: A boolean to see whether or not the toast was closed via click.
    • Second parameter: The whole toast that got hidden.
  • onShown: A callback function called when a toast is shown.
    • First parameter: The whole toast that got shown.
  • onTap: A callback function called when it is clicked.
    • First parameter: The whole toast that got clicked.

The second option is to pass a third parameter (or second if you don't need a title). Let see some examples:

Toast with custom HTML (available in both title and message):

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

Html Image

Toast with a close button:

toastr.success('What a nice button', 'Button spree', {
  closeButton: true
});

Html Image

Toast with a custom button for apple fans:

toastr.info('What a nice apple button', 'Button spree', {
  closeButton: true,
  closeHtml: '<button></button>'
});

Html Image

A pinky custom style (you can also create here new types with $decorate):

toastr.info('I am totally custom!', 'Happy toast', {
  iconClass: 'toast-pink'
});

toast-pink is a custom class created for the occasion:

.toast-pink {
    background-image: url(...) !important;
    background-color: #fa39c3;
}

Pink image

Toast template

If you want to use the built-in template, you can use the angular-toastr.tpls.js file.

If you decide that you don't want to use the built-in one, you can always use angular-toastr.js file and then providing your own template like this:

angular.module('yourApp').run(['$templateCache', function($templateCache) {
  $templateCache.put('directives/toast/toast.html',
    "<div>Your template here</div>"
  );
  $templateCache.put('directives/progressbar/progressbar.html',
    "<div>Your progressbar here</div>"
  );
}]);

The important part here is to have a key named templates/toastr/toastr.html. The module you run it is not important, you just need to do it after you load toastr.

NOTE: Due some limitations in Angular, you need to have your custom template cached before trying to use it.

Building

If you want to build from master, you need to:

$ npm install -g gulp
$ npm install
$ gulp production

Grab the compressed files under /dist and the dev files at /gen.


FAQ

Q: Why can't I override the positionClass in a toast? It gets ignored. A: The toasts don't have a position, they are attached to a container and is that container who has the position set on the page. This will be changed in a future version.

Libraries using angular-toastr

Credits

All the credits for the guys at CodeSeven/toastr for creating the original implementation.

License

Mit License: http://www.opensource.org/licenses/mit-license.php

angular-toastr's People

Contributors

aaronroberson avatar chrisg2 avatar emiljanitzek avatar erkez avatar foxandxss avatar jcford73 avatar luckycadow avatar lukasdrgon avatar mrzepinski avatar naz avatar npmcdn-to-unpkg-bot avatar olso avatar prayagverma avatar realityking avatar sroe avatar timbell avatar tlvince avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-toastr's Issues

Fast dismissing of toasts results in preserving them

If I create multiple toasts(really fast) and then try to dismiss them fast(by clicking on them) at some point one of the toasts is not removed and it is not dismissed after the timeout. I know that this is sort of spamy but it is annoying(I have to refresh the page to remove the toast)

Note that this happens with dismiss on click and a dedicated close button(not sure if this is relevant)

How to dismiss a sticky toast

If a sticky toast is created like this:

toastr.success('I am sticky', 'Title', { timeOut: 0, extendedTimeOut: 0 });

How do I then dismiss it? Is there a command for closing a toast?

Thank you

$animate.leave only gets called after digest?

Hi,
I'm having these lines of code:

$document.find('body').on('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart', dismissToast);
function dismissToast() {
                    toastr.clear();
                  }
                $document.find('body').off('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart', dismissToast);
              };

In short: It should close all toasts if the user came back from being idle.
clear gets called and $animate.leave() too, but the toasts stay until a digest loop gets called.
Am I missing something or is the only solution to call $digest() on $rootScope inside my dismissToast function?
Regards

Which version to use for angular 1.2.*?

Hi,
tried to work with this module, but it does not work with angular 1.2.* as $animate.enter() returns no promise before 1.3. angular-toastr is using that promise which causes issues in my application.
So is there a version of angular-toastr which i can use with angular version < 1.3 ?

Add to ngmodules.org

You should add you project to ngmodules.org to get it easier found, I was searching for some port and found your project by accident.
I like your documentation 👍, that's what the other libraries miss which I have looked at on ngmodules.
Is it possible to get a bit more comments inside your Code ❓

Disable toastr extendedTimeOut option

Hi,
is there any way to disable a toaster option extendedTimeOut how the notifications would not disappear when is mouse hovered over it.
It's not the solution assign some value to this option like 50000. I would appreciate more smoother way to set this.
Thanks!

onShown, onHidden never fire

toastr.warning('something', null, {onShown: function(){
console.log('something');
})

Console.log will never be displayed. I'm using latest version via bower. Do anybody have this issue?

Dismiss programatically

I want to use this toast to show loading indicator (especially in http request). However, I would never know how long a http request would take so I cannot use timeout parameter to control the toast. I want to fire a loading toast before http request and close it in response callback without a user interaction.

Any way to do that?

Error when using http requests queue

Hi

I'm using You script -it's great.
I've got one problem.
If I add that code to my app config I always get error on first toaster

TypeError: undefined is not a function
    at http://root.system.local/bower_components/angular-toastr/dist/angular-toastr.tpls.js:142:30
    at processQueue (http://root.system.local/bower_components/angular/angular.js:13170:27)

Here is code - it is responsible for queueing requests to server.

.config(['$httpProvider', function ($httpProvider) {
            /**
             * Interceptor to queue HTTP requests.
             */
            $httpProvider.interceptors.push(['$q', function ($q) {
                var _queue = [];

                /**
                 * Executes the top function on the queue (if any).
                 */
                function _executeTop() {
                    if (_queue.length === 0) {
                        return;
                    }
                    _queue[0]();
                }

                return {
                    /**
                     * Blocks each request on the queue. If the first request, processes immediately.
                     */
                    request: function (config) {
                        var deferred = $q.defer();
                        _queue.push(function () {
                            deferred.resolve(config);
                        });
                        if (_queue.length === 1) {
                            _executeTop();
                        }
                        return deferred.promise;
                    },
                    /**
                     * After each response completes, unblocks the next request.
                     */
                    response: function (response) {
                        _queue.shift();
                        _executeTop();
                        return response;
                    },
                    /**
                     * After each response errors, unblocks the next request.
                     */
                    responseError: function (responseError) {
                        _queue.shift();
                        _executeTop();
                        return $q.reject(responseError);
                    },
                };
            }]);
        }])

Error occurs only in first toaster - then everything is ok.

positionClass is considered a bad option?

Hi,

I noticed the the positionClass cannot be overriden per toast
when i use:

$http(...).error(function(e){
    toastr.error(e.exceptionMessage, e.message, { "positionClass": "toast-top-full-width"});
});

The positionclass will be removed from the options, which is done by:

function cleanOptionsOverride(options) 
{
    var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop',
                    'positionClass', 'preventDuplicates', 'templates'];
    for (var i = 0, l = badOptions.length; i < l; i++) {
        delete options[badOptions[i]];
    }

    return options;
}

I wonder why this is. I could set this as a config obviously, but i would like to override.

Kind regards

Discussion about allowing HTML

I want to discuss here of what should we do about trusting html.

I saw various ways, and I am not sure of any of them:

As today, you can add html onto it, $sce will trust your html but I am unsure how it works vs XSS. Using ngSanitize is also an option, but it doesn't allow to use form items on the toast.

The problem with $sce is that you can't put directives into the trusted HTML (that is intended). That doesn't mean I can create a directive where you can put any kind of html on your toast (even forms that will work with your scope), but that is highly insecure.

I want to discuss what are your thoughts about this.

Progress Bar

Compliments for the nice and simple plugin!
The only thing missing is the Progress Bar ... wil this be included in a future version?

Toastr container is not a jqLite object

In _createOrGetContainer() the target container for toastr is found using document.querySelector() and is passed into $animate.enter(). This throws an exception as $animate.enter() is expecting a jqLite object.

Feature Request: on-click option for defining what happens on tap

Upon logging in, I'm polling an API call and checking if the user has any new message. If the user does have new messages, I'm displaying a toastr to say "You have received a new message".

I figured it would be cool if I could define what happens upon tapping the toastr message. So tapping this one in particular would take the user to his inbox to read the new message.

At the moment tapping a toastr can only dismiss it but we could do so much more. What do you think?

Change the text color

I see an option to change the background color. If I set it to a lighter one, the default text color of White is not visible enough. Do we have an option to change the color of the icon, text displayed and the Close button, which is White by default?

Support Toastr's newestOnTop config

I noticed after switching from pure JS Toastr implementation over to Angular-Toastr that my new toasts were being added to the bottom of the list. This has an unfortunate side effect of making the fade-out look a little jumpy. I thought at first that changing this behavior would just be a matter of changing toastrConfig like...

toastrConfig.newestOnTop = true;

But this didn't seem to have any impact. Next I dug into the source code. Here's the relevant bit of the Toastr source:

function addToast(toast) {
  // Hidden for brevity
if (mergedConfig['newest-on-top'] === true) {
  scope.toasters.unshift(toast);
  // Hidden for brevity
} else {
  scope.toasters.push(toast);
  // Hidden for brevity
}

I'm not sure this is quite so straight forward to implement in your version of Toastr because of how you're using $animate.enter but I think a similar thing could be accomplished by making the following two changes:

Assign a placeholder first child in setContainer
container = angular.element('<div><i></i></div>'); // <i> could be any other inline element
Check toastrConfig and parent the new toast appropriately in _notify
_setContainer(options).then(function() {
  var after = toastrConfig.newestOnTop ? container.find('i') : null; // You could change the default

  $animate.enter(newToast.el, container, after, function() {

Any chance you could make this change?

PS. For what it's worth, I tested this change locally and it seems to work. I'll submit a PR shortly.

Delay on click to dismiss

Hello,

When I click the toast, I am seeing a delay, .5s to 1s, before the toast actually disappears. Is this intended behaviour, or am I doing something totally wrong... my config is...

// toastr config
  _.extend(toastrConfig, {
    toastClass: 'toast animated fadeInDown',
    tapToDismiss: true
  });

and I have a service making use of it...

self.toastr.info('blah blah blah', {
      onHidden: function() {
        console.log(arguments);
      }
    });

Thank you,

--d

NPM Publishing

It'd be great if you were published on NPM so I could just user Browserify; I'm trying to get rid of my Bower.json :)

Docs wrong

For your .config() section you have improper code. I'm not sure the best way you want to go about it, but this is what I did:

app.config(function(toastrConfig) {
  angular.extend(toastrConfig, {
    timeOut: 100
  });
});

$timeout prevents protractor testing

$timeout prevents protractor testing. Protractor waits for $timeout to complete before it allows you to continue. Instead it is recommended to use $interval(callback,time,1).

Possible issue with maxOpened

If the toasts are opened THAT fast, the restriction is no longer respected and toasts gets sticked.

Need to research about that.

Add the template path to the toastrConfig constant

It would be really nice if the template path were configurable rather than hard coded. I use an html2js build process that puts templates in the $templateCache based on directory structure. While using .run to add my custom template to the hard coded location works; I'd like my "alerts" module directory to have an alerts.tpl.html file that gets swallowed up by my build process and then is recognizable by angular-toastr through something like this

angular.extend(toastrConfig, { templatePath:'alerts/alerts.tpl.html'})

Angular 1.2.x compatibility

Does Angular-Toastr 5.0 work with angular 1.2.x? As far as I saw, there is no compatibility cuz $animate.enter() returns a promise in Angular 1.3.x and not in Angular 1.2.x. Then the code following code fails to execute in Angular 1.2.x

      $animate.enter(container, body).then(function() {
        containerDefer.resolve();
      });

For supporting 1.2.28,you have to change some code.

As Angular below version 1.3 doesn't support Promise

When I use Toastr in my Angular project whose angular version is 1.2.28 , I have to change some codes. I display some of them, it may help.

at line 59

   $animate.leave(toast.el, function() {
          if (toast.scope.options.onHidden) {
            toast.scope.options.onHidden(wasClicked);
          }
         ....

at line 124

$animate.enter(container, body, '', function() {
        containerDefer.resolve();
      });

at line 145

if (options.newestOnTop) {
            $animate.enter(newToast.el, container, '', function() {
              newToast.scope.init();
            });
          } else {
            $animate.enter(newToast.el, container, container[0].lastChild,function() {
              newToast.scope.init();
            });
          }

iconClass option is not actually an iconClass option

The Icon Class option sets the class of the toast element somewehere in the root element and is also used for the background-color of the toast.
The way the icon is set (as background image / base64 encoded) makes it hard to use another icon provider (e.g. from FontAwesome, Glyphiccons, etc).

show/hideEasing not working

The toastr message appears but without an animation. This properties can be handle from .config?

My version of angular is 1.3.2 with it's respective ngAnimate.

Cannot read property 'then' or undefined

Hi guys,

I followed all instructions mentioned in the documentation of using angular-toastr and I did everything step by step, but always I get the same error:

TypeError: Cannot read property 'then' of undefined
at _createOrGetContainer (angular-toastr.tpls.js:120)
at angular-toastr.tpls.js:139

$animate.enter(body, container) return undefined --> error on 'then' call

My Angular Version 1.2.27
don't have import ng-animate out from angular.js

I think it's a syntax problem. I solved change in this way (about row 153)

$animate.enter(container, body, null, function() {
containerDefer.resolve();
});

instead

$animate.enter(container, body).then(function() {
containerDefer.resolve();
});

$animate.enter(container, body) returned undefined (every call $animate.enter return that so i changed all of them)

Thank you

toastr has stopped working, it's attempting to load a template file

I bower updated my project today and toastr has stopped working. When ever I try to pop a message I get this error from angular.

Error: [$compile:tpload] Failed to load template: templates/toastr/toastr.html

I can't see this change documented anywhere, what has caused this and what needs to be changed in my project to get toastr to work again.

Seems like leaving the page stops the timeout

When playing with the demo, if I get focus on another window in the other monitor, the timeout are never triggered.

Need to research that but if someone have an idea, PR it please.

EDIT: Only happens something. There are toasts that never leaves and toasts that are stuck on the view.

Library ToDo

There are the things I want to accomplish for the first release:

  • Animations
  • More types of animations
  • Callback/promise when finish
  • Be able to change the stacking order (Issue #6275)
  • Override options per toastr
  • Proper tests :)
  • Remove last / all toastr
  • Custom templates (Something to investigate)
  • Awesome demo
  • Sticky toasts

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.