Giter Club home page Giter Club logo

angular-notify's Introduction

#angular-notify

A minimalistic (and extensible) notification service for Angular.

Live Demo

Supports IE 10, and recent versions of FF and Chrome.

Getting Started

Install with Bower, npm, or download the the files directly from the dist folder in the repo.

bower install angular-notify --save
npm install @cgross/angular-notify`

Add dist/angular-notify.js and dist/angular-notify.css to your index.html.

Add cgNotify as a module dependency for your module.

angular.module('your_app', ['cgNotify']);

Then inject and use the notify service.

function myController($scope,notify){  // <-- Inject notify

  notify('Your notification message'); // <-- Call notify with your message

  notify({ message:'My message', templateUrl:'my_template.html'} );

}

Options

notify(String|Object)

The notify function can either be passed a string or an object. When passing an object, the object parameters can be:

  • message - Required. The message to show.
  • duration - Optional. The duration (in milliseconds) of message. A duration of 0 will prevent messages from closing automatically.
  • templateUrl - Optional. A custom template for the UI of the message.
  • classes - Optional. A list of custom CSS classes to apply to the message element.
  • messageTemplate - Optional. A string containing any valid Angular HTML which will be shown instead of the regular message text. The string must contain one root element like all valid Angular HTML templates (so wrap everything in a <span>).
  • scope - Optional. A valid Angular scope object. The scope of the template will be created by calling $new() on this scope.
  • position - Optional. center, left and right are the only acceptable values.
  • container - Optional. Element that contains each notification. Defaults to document.body.

This function will return an object with a close() method and a message property.

notify.config(Object)

Call config to set the default configuration options for angular-notify. The following options may be specified in the given object:

  • duration - The default duration (in milliseconds) of each message. A duration of 0 will prevent messages from closing automatically.
  • startTop - The Y pixel value where messages will be shown.
  • verticalSpacing - The number of pixels that should be reserved between messages vertically.
  • templateUrl - The default message template.
  • position - The default position of each message. center, left and right are the supported values.
  • container - The default element that contains each notification. Defaults to document.body.
  • maximumOpen - The maximum number of total notifications that can be visible at one time. Older notifications will be closed when the maximum is reached.

notify.closeAll()

Closes all currently open notifications.

Providing Custom Templates

Angular-notify comes with a very simplistic default notification template. You are encouraged to create your own template and style it appropriate to your application. Templates can also contain more advanced features like buttons or links. The message templates are full Angular partials that have a scope (and a controller if you use ng-controller="YourCtrl").

The scope for the partial will either be descended from $rootScope or the scope specified in the notify({...}) options. The template scope will be augmented with a $message property, a $classes property, and a special $close() function that you may use to close the notification.

The messageTemplate property is also included on the scope as $messageTemplate. To ensure your custom template works with the messageTemplate option, your template should hide the normal text if $messageTemplate contains a value, and should have an element with the cg-notify-message-template class. The element with the cg-notify-message-template class will have the compiled template appended to it automatically.

Release History

  • v2.5.1 - 01/05/2017
    • Fixed for Angular 1.6 promise method changes.
    • Published to NPM.
  • v2.5.0 - 04/12/2015
    • New duration property per notification.
    • New position property per notification.
    • Fix for DOM elements not being removed.
    • New maximumOpen config option.
    • Bump Angular dependency to 1.3.
  • v2.0.2 - 09/06/2014
    • Default template redesigned with a Bootstrap look and feel. Default template now also includes a close button.
    • Default message location is now the top center.
    • Default message duration is now 10 seconds.
    • Default verticalSpacing is now 15px.
    • The template option was renamed to templateUrl.
    • New messageTemplate option added.
    • New classes option added.
    • Fixed an issue causing a message with multiple lines of text to be placed into the visible area too soon.
    • Fixed #4 (config() not correctly setting startTop)
  • v1.1.0 - 5/18/2014 - Added return value allowing for closing and updating of message.
  • v1.0.0 - 4/16/2014 - Significant refactoring.
  • JQuery is no longer a required dependency.
  • [Breaking Change] Configure the default template using config() now instead of the cgNotifyTemplate value.
  • [Breaking Change] The verticalSpacing parameter should no longer include the height of the notification element.
  • [Breaking Change] The scope options must now be a valid Angular scope.
  • [Breaking Change] The duration of the notifications is now based on a duration config property and does not rely on the delay attribute of the CSS transition.
  • Messages can now word wrap if you use a max-width css value.
  • The scope for templates now includes a $close() function.
  • New notify.closeAll() method.
  • v0.2.0 - Adding custom templates ability, fixed FF bug.
  • v0.1.0 - Initial release.

angular-notify's People

Contributors

cgross 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

angular-notify's Issues

Bump angular version

You should really consider to bump your angular dependency version or at least not to lock the minor using within your bower.json

sometime the notify is not working.

Some time the notify is not working. I don't know what will be the reason. There is no error message or anything. The notify doesn't show anything.

Does angular-notify not work with Angular 1.3*?

When I bower install angular-notify --save I got the following message:


Unable to find a suitable version for angular, please choose one:
    1) angular#~1.2 which resolved to 1.2.28 and is required by angular-notify#2.0.2
    2) angular#1.3.10 which resolved to 1.3.10 and is required by angular-resource#1.3.10
    3) angular#>= 1.0.8 which resolved to 1.3.10 and is required by angular-ui-router#0.2.13
    4) angular#~1.3.9 which resolved to 1.3.10 and is required by console
    5) angular#* which resolved to 1.3.10 and is required by angular-smart-table#1.4.8Prefix the choice with ! to persist it to boer.json

? Answer:: 2
bower angular-notify#~2.0.2    install angular-notify#2.0.2

I picked 1.3.10 and my notification does not seem to appear.

Stop onmouseover

Hi,

A "stop delay before hide" function on mouse over will be great!

Version conflict

$ bower install angular-notify --save
bower angular#1.5.3 cached git://github.com/angular/bower-angular.git#1.5.3
bower angular#1.5.3 validate 1.5.3 against git://github.com/angular/bower-angular.git#1.5.3
bower ECONFLICT Unable to find suitable version for angular

Change animation speed

Hey there!
Thx for very nice plugin.

I was wondering - is there any way of changing animation speed or easing?
Default speed is very slow.

IE9 Support.

Whats missing for IE9 support Anything we can do?

Issue with notifications on Safari

Hey! Thanks for the very nice Angular module. We are using it for a big project and ran into a bug this morning while testing on ios. On Chrome stable and Chrome dev on android the notifications work perfectly and scale to the sceen size nicely as seen in this screenshot.
chrome

But on ios 8.3 with safari mobile 8 the notifications are halfway off screen as seen in this screenshot:
keannotifybug

I know its just a css issue most likely and am willing to help fix it. Just wanted to see what you had to say on it and if you can point me in the right direction.

Consider upgrading to Angular 1.4

Is there any reason why Angular ~1.4 wouldn't work? Right now, this is the only dependency on my current project that forces me to use "resolutions" on bower.json.

Improve documentation

I was running into problems because message templates did not have one root element only. Only today I found a sentence in the documentation mentioning this requirement. However, it could still be formulated more precisely. Maybe you could change it to something like:

messageTemplate - Optional. A string containing any valid Angular HTML which will be shown instead of the regular message text. The string must contain one root element only like all valid Angular HTML templates. For instance, wrap everything in a <span>.

Default position bug in V2.5.0

I have installed V2.0.2 and default notifications are working good with center alignment but in latest release it's breaking i.e. V2.5.0.
margin-left style is missing in latest version custom templates.

Support for per-message duration

Hi

It would be cool if the module would support configuring the duration for a message individually. At the moment one can only set the duration globally for any message. Adding duration as an optional property to the objects argument of notify(), that, if set, overwrites the global duration, seems to be what is needed to enable this.

Thanks

Messages dont really disappears

I'm doing a big app for the company I work for and I'm using this module. The module works fine, the template part is good too and it's very customizable.

But when we come to the $close() function we have a problem. When you do this:

templateElement.css({'opacity' : 0}).attr('data-closing','true');

You are basicaly keeping the element in the page instead of really hidding or removing him. This may cause some problems with other elements in the same page (it was in my case).

My solution? Change the line above, to this:

templateElement.css({'display' : 'none'}).attr('data-closing','true');

By using display: none the element will disappear from the sight and don't will interfere the other elements around him.

Just FYI the problem I was having was with the close button in the top right position inside the message. When I had more than 10 messages displayed I was clicking in the button and the click area was changing, so if the user clicked in the close icon, the message didnt closed, only if he moved the mouse a little higher.

Publish on npm

Is there anyway you could publish this module on npm?

Consider publishing to npm

I tend to use only npm these days and not bother with bower. This is one of the few client side packages I can't install via npm. Publishing is a piece of cake, just run npm publish.

This is normal??

1
2
3

I use notify as factory.

.factory('Notify', function ($rootScope, notify) {

    function openNotify(notifyMessage, notifyClass) {
      var positions = ['center', 'left', 'right'],
          position = positions[2],
          duration = 10000;
      notifyClass = notifyClass || 'alert-info'; 

      return notify({
            message: notifyMessage,
            classes: notifyClass,
            templateUrl: 'components/notify/notify.html',
            position: position,//not respect right, show left every time
            duration: duration
          });
    }

    // Public API here
    return {

      notifycation: {


       show: function(callback) {
          callback = callback || angular.noop;

          return function() {
            var args = Array.prototype.slice.call(arguments),
                text = args.shift(),
                customClass = args.shift(),
                showNotify;

            showNotify = openNotify(text, customClass);      

            //callback.apply(event, args);//for future
          };
        }
      }
    };
  });

And i call from controller

$scope.showNotify =  Notify.notifycation.show(function(args) {
      console.log(args);//future callback
    });

var _message = 'Hello World',
      _class = 'alert-info';

$scope.showNotify(_message, _class);

notifyProvider?

I wanted to place an $httpProvider.interceptors to globally prompt about erroneous requests, but it seems cgNotify does not contain a provider for this.

How to config?

I get an error (Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: notify when I do something like this:

app.config( function(notify) {

})

How can I inject the notify service in the config?

Display notification(s) at the bottom instead of top

Hi there,

Thanks for this very useful Angular module.

Because I needed to modify notifications to be able to display them at the bottom of the page, I've forked and modified its code - maybe someone also will look for the same issue, so I've prepared working version available here:

https://github.com/bl4de/angular-notify/tree/master/at-the-bottom

Maybe I should create 'mixed' version with both options and send you some PR for reviewing? What do you think? Let me know in comment ;)

Regards,

R.

Another callback at $close()?

Thanks for your nifty module here! - Say, is it possible to implement some additional callback on the close-button? I would like to set a variable to true/false, when the window is closed (e.g. to disable buttons as long as a notification is open...)

Thanks!

click events don't work when ionicModal or ionicPopup are displaying....

http://stackoverflow.com/questions/36295476/ionicmodal-disabling-click-events

Here is the text of the question repeated here:

Ionic/cordova/angular/ios application:

I am using angular-notify to display overlay messages that have ng-click events attached. They show up fine and the ng-click events register EXCEPT when an ionicModal is open - while it's open and an angular-notify message displays, I can't click it. As soon as I click to close the modal (I have to click on my notification since it is overlaying the close button but it still closes the modal) the ng-click registers again.

I am not sure how to test this theory, but it feels like the click is getting captured or disabled by ionicModal. Is there something I can do (z-index is set to 99999) to make those clicks get registered?

-- UPDATE (Testing in Chrome w/inspector)

It doesn't appear to matter in which order the elements are loaded. Whether the modal, notification overlay or popup load in first, the issue remains.

Click events are cut off for my notification overlay until the modal and/or popup are dismissed.

When I look at the DOM inspector, I see some divs are created when the popup or modal instantiates. This one:

looks like it might be causing my issues but it sits lower in the DOM and when I delete the element (in Chrome Inspector) it doesn't fix my issue.

No matter what z-index I set or where I move the element in the DOM (via inspector) or what background div elements I delete, I still cant click my notification until any and all popup/modals are dismissed.

Any thoughts?

cdep on $http for global notifications

Hi, I really like the simplicity of this module and I tried implementing it today.

I thought the perfect case for these notifications would be global Ajax message handling, but the interceptors are dependencies of the $http module. Apparently the cgNotify module also uses $http as a dependency. As a consequence there is an angular cdep (circular dependency) error.

Any suggestions on how to use your module for global message handling?

Check console for cdep error:
http://plnkr.co/edit/Wlnl6wdOsC5pDVZRgZgs?p=preview
Same code working with notify dependency in comment for the interceptor:
http://plnkr.co/edit/S7v9Lcon7SGkGVjDZD8d?p=preview

messageTemplate issue / proposal

Hi,

if the class cg-notify-message-template is not a direct child of cg-notify-message element, notify can't find it.
it can be a problem when you use a custom template.
Moreover, use 2 differents elements (message and messageTemplate) is not very obvious and once again custom template are not clean.

I send my code as a suggestion for clean support for html (it's a coffescript with class style code)

Filter for trust HTML in $message

class TrustHTML

  constructor: ($sce) ->
    return (message) ->
      return $sce.trustAsHtml(message)

@app.filter 'trustHTML', ['$sce', TrustHTML]

Config notify with custom template (use of ng-bind-html with trustHTML filter)

class ConfigNotify

  constructor: (notify, $templateCache) ->

    # Global config
    notify.config
      duration: 4000
      startTop: 10
      verticalSpacing: 10
      maximumOpen: 3


    # Custom templates
    notifyDangerTpl = [
      '<div class="cg-notify-message cg-notify-message-center alert-danger" ng-style="{\'margin-left\': $centerMargin}">'
        '<table>'
          '<tr>'
            '<td class="cg-notify-icon"><i class="fa fa-warning"></i></td>'
            '<td class="cg-notify-content" ng-bind-html="$message | trustHTML"></td>'
            '<td class="cg-notify-button"><button type="button" class="cg-notify-custom-close" ng-click="$close()"><i class="fa fa-close"></i></button></td>'
          '</td>'
        '</table>'
      '</div>'
    ].join('')

   $templateCache.put('notify-danger.html', notifyDangerTpl)

@app.run ['notify', '$templateCache', ConfigNotify]

How to use ?

notify
   templateUrl: 'notify-danger.html'
   message: "A custom template with <b>trusted HTML</b>"

Result
image

shadowHeight

I'm mostly interested in using this as a barebones driver for my own message template, and I realized the positioning was getting really out of sync as multiple messages were shown.

It appears that there is a hardcoded spacing of 10px that is causing me problems:

var shadowHeight = 10;

It would be convenient to have this assumption removed so that custom templates aren't confused by the subsequent bad math (increasingly 10px off the target positioning with each new message).

classes

notify({
classes: 'alert-danger',
message: $scope.validator[x][0]
});

but thats notify still show blue color, how to make it works?

On default only one notify should be allowed

If I am calling notify on click, for each click a notify is triggered. There should be an option to set closeAll as part of config, so that currently open notify get close before triggering a new one.

When notify is used in multiple controllers, its redundant to call notify.closeAll() many times.

dispatch some events

notify should dispatch event on returned object on closed, opened and clicked

Not working on ngDialog

If ngDialog pop up is open then Notify alert always pops up behind ngDialog. Is there any way to fix it? Or it is a bug? Plz help. If Notify can't show messages on ngDialog then I need to look for some other plugin. Thank you!!!

Not working on ngDialog

If ngDialog pop up is open then Notify alert always pops up behind ngDialog. Is there any way to fix it? Or it is a bug? Plz help. If Notify can't show messages on ngDialog then I need to look for some other plugin. Thank you!!!

Add $title var

It would be very helpful for some case add a title for message. And I think for this is a very quick implementation of code.

Can I do pull request?

Allow .cg-notify-message-template in elements not in the imediate child list

I ran into this recently. Currently, if the element containing .cg-notify-message-template is not a child of the root element in the template, cgNotify throws an error: "cgNotify could not find the .cg-notify-message-template element in..."

To work around it is pretty simple, and I wrote a code to do so.
Just replace lines 43-49 in angular-notify.js:

                    var messageTemplateElement;
                    for (var i = 0; i < templateElement.children().length; i ++){
                        if (angular.element(templateElement.children()[i]).hasClass('cg-notify-message-template')){
                            messageTemplateElement = angular.element(templateElement.children()[i]);
                            break;
                        }
                    }

with this:

                    var fnRecursiveLook = function (myElement) {
                        var children = myElement.children();
                        for (var i = 0; i < children.length; i++) {
                            var child = angular.element(children[i]);
                            if (child.hasClass('cg-notify-message-template')) {
                                return child;
                            }
                            if (child.children().length > 0) {
                                return fnRecursiveLook(child);
                            }
                        }
                        return undefined;
                    };
                    var messageTemplateElement = fnRecursiveLook(templateElement);

protractor tests : using $interval instead of $timeout for notify duration management

Hi,

I use this module in my application, and I started to write e2e tests with protractor.
There is no problem when writing tests for function using notification which stay on screen, but notification with duration attribute are not testable. This issue comes from the $timeout service to manage notification duration : protractor waits for $timeouts (and $http) before to run actions and expectation. So notification with duration can't be tested as they disappears before protractor tests them.
In documentation (https://github.com/angular/protractor/blob/master/docs/timeouts.md), protractor team precognise to replace $timeout services by $interval services to this kind of issue.

Can you try that to allow protractor testing of notifications with duration ?

notify div is not removed from DOM when transitionend event is not fired

I've noticed an intermittent issue where

element housing the notification message is not always removed from the DOM after it is faded out (i.e. after the opacity is set to 0). This results in the transparent notification message obscuring part of the screen, preventing it from receiving mouse clicks or touch events.

The problem seems to be this code:

                var templateElement = $compile(template)(scope);
                templateElement.bind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd', function(e){
                    if (e.propertyName === 'opacity' || e.currentTarget.style.opacity === 0 || 
                        (e.originalEvent && e.originalEvent.propertyName === 'opacity')){

                        templateElement.remove();

transitionend event isn't always sent by the browser - an instance may be when the transition is interrupted by another process. This means that the element may not get removed where the event isn't fired.

custom layout not being parsed on first notify() call after app load

weirdly, the first time I use notify() to display a notification after the app loads, i'm seeing the {{$message}} instead of the rendered message, like if angular wasn't parsing the template html.

i'm not sure if it's a bug on cgNotify itself or a bad implementation on my code.
my code is as simple as this:

template html:

<article class="notification" ng-class="{'is-notice': notify.type == 'notice', 'is-success': notify.type == 'success', 'is-error': notify.type == 'error'}">
  <h2 class="h-article" ng-if="notify.title">{{notify.title}}</h2>
  {{$message}}
</article>

notify() call:

$scope.notify = {type: 'alert'};
notify({
    message: 'acesso não permitido.',
    template: 'views/common/notification.html',
    position: 'center',
    scope: $scope
});

do you guys have any clue on it?
thanks!

Duration set to 0 not work

In line 21
args.duration = args.duration ? args.duration : defaultDuration;
If duration is set to 0, args.duration equals defaultDuration and it violates the doc

duration - Optional. The duration (in milliseconds) of message. A duration of 0 will prevent messages from closing automatically.

CDNJS

This is very very good plugin! Congratulations!

Maybe you can deliver this plugin in some js cdn site, like cdnjs.com or jsdelivr.com, for people make a fast test

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.