Giter Club home page Giter Club logo

angular-moment's Introduction

angular-moment

AngularJS directive and filters for Moment.JS.

Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018 Uri Shaked [email protected]

Build Status Coverage Status

New Angular version is now available: ngx-moment


Installation

You can choose your preferred method of installation:

  • Through bower: bower install angular-moment --save
  • Through npm: npm install angular-moment moment --save
  • Through NuGet: Install-Package angular-moment Moment.js
  • From a CDN: jsDelivr or CDNJS
  • Download from github: angular-moment.min.js

Instructions for using moment-timezone with webpack

Even if you have moment-timezone in your package.json, angular-moment will not be able to use it unless you override moment using Angular's dependency injection See Resolved Issue

var angular = require('angular');
require('angular-moment');
var ngModule = angular.module('ngApp',['angularMoment']);
ngModule.constant('moment', require('moment-timezone'));

Usage

Include both moment.js and angular-moment.js in your application.

<script src="components/moment/moment.js"></script>
<script src="components/angular-moment/angular-moment.js"></script>

Add the module angularMoment as a dependency to your app module:

var myapp = angular.module('myapp', ['angularMoment']);

If you need internationalization support, load specified moment.js locale file right after moment.js:

<script src="components/moment/moment.js"></script>
<script src="components/moment/locale/de.js"></script>
<script src="components/angular-moment/angular-moment.js"></script>

Then call the amMoment.changeLocale() method (e.g. inside your app's run() callback):

myapp.run(function(amMoment) {
	amMoment.changeLocale('de');
});

Use in controller/service/factory

Inject the moment-constant into your dependency injection. For example:

angular.module('fooApp')
    .controller('FooCtrl', ['$scope', 'moment', function ($scope, moment) {
        $scope.exampleDate = moment().hour(8).minute(0).second(0).toDate();
    }]);

am-time-ago directive

Use the am-time-ago directive to format your relative timestamps. For example:

<span am-time-ago="message.time"></span>

angular-moment will dynamically update the span to indicate how much time passed since the message was created. So, if your controller contains the following code:

$scope.message = {
   text: 'hello world!',
   time: new Date()
};

The user will initially see "a few seconds ago", and about a minute after the span will automatically update with the text "a minute ago", etc.

amParse filter

Parses a custom-formatted date into a moment object that can be used with the am-time-ago directive and the other filters. For example, the following code will accept dates that are formatted like "2015.04.25 22:00:15':

<span am-time-ago="message.time | amParse:'YYYY.MM.DD HH:mm:ss'"></span>

amFromUnix filter

Converts a unix-timestamp (seconds since 1/1/1970) into a moment object. Example:

<span am-time-ago="message.unixTime | amFromUnix">

amUtc filter

Create / switch the current moment object into UTC mode. For example, given a date object in message.date, the following code will display the time in UTC instead of the local timezone:

<span>{{message.date | amUtc | amDateFormat:'MM.DD.YYYY HH:mm:ss'}}</span>

amUtcOffset filter

Uses the given utc offset when displaying a date. For example, the following code will display the date with a UTC + 3 hours time offset:

<span>{{message.date | amUtcOffset:'+0300' | amDateFormat:'MM.DD.YYYY HH:mm:ss'}}</span>

amLocal filter

Changes the given moment object to be in the local timezone. Usually used in conjunction with amUtc / amTimezone for timezone conversion. For example, the following will convert the given UTC date to local time:

<span>{{message.date | amUtc | amLocal | amDateFormat:'MM.DD.YYYY HH:mm:ss'}}</span>

amTimezone filter

Applies a timezone to the given date / moment object. You need to include moment-timezone.js in your project and load timezone data in order to use this filter. The following example displays the time in Israel's timezone:

<span>{{message.date | amTimezone:'Israel' | amDateFormat:'MM.DD.YYYY HH:mm:ss'}}</span>

amDateFormat filter

Format dates using moment.js format() method. Example:

<span>{{message.time | amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a'}}</span>

This snippet will format the given time as "Monday, October 7th 2013, 12:36:29 am".

For more information about Moment.JS formatting options, see the docs for the format() function.

amCalendar filter

Format dates using moment.js calendar() method. Example:

<span>{{message.time | amCalendar:referenceTime:formats}}</span>

This snippet will format the given time as e.g. "Today 2:30 AM" or "Last Monday 2:30 AM" etc..

For more information about Moment.JS calendar time format, see the docs for the calendar() function.

amDifference filter

Get the difference between two dates in milliseconds. Parameters are date, units and usePrecision. Date defaults to current date. Example:

<span>Scheduled {{message.createdAt | amDifference : null : 'days' }} days from now</span>

This snippet will return the number of days between the current date and the date filtered.

For more information about Moment.JS difference function, see the docs for the diff() function.

amDurationFormat filter

Formats a duration (such as 5 days) in a human readable format. See Moment.JS documentation for a list of supported duration formats, and humanize() documentation for explanation about the formatting algorithm.

Example:

<span>Message age: {{message.ageInMinutes | amDurationFormat : 'minute' }}</span>

Will display the age of the message (e.g. 10 minutes, 1 hour, 2 days, etc).

amSubtract filter

Subtract values (hours, minutes, seconds ...) from a specified date.

See Moment.JS documentation for a list of supported duration formats.

Example:

<span>Start time: {{day.start | amSubtract : '1' : 'hours' | amDateFormat : 'hh'}} : {{day.start | amSubtract : '30' : 'minutes' | amDateFormat : 'mm'}}</span>

amAdd filter

Add values (hours, minutes, seconds ...) to a specified date.

See Moment.JS documentation for a list of supported duration formats.

Example:

<span>Start time: {{day.start | amAdd : '1' : 'hours' | amDateFormat : 'hh'}} : {{day.start | amAdd : '30' : 'minutes' | amDateFormat : 'mm'}}</span>

amStartOf filter

Mutates the original moment by setting it to the start of a unit(minute, hour, day..) of time.

See Moment.JS documentation for a list of supported duration formats.

Example:

<span>{{ date | amStartOf:'month' | amLocal }}</span>

amEndOf filter

Mutates the original moment by setting it to the end of a unit(minute, hour, day..) of time.

See Moment.JS documentation for a list of supported duration formats.

Example:

<span>{{ date | amEndOf:'month' | amLocal }}</span>

Time zone support

The amDateFormat and amCalendar filters can be configured to display dates aligned to a specific timezone. You can configure the timezone using the following syntax:

angular.module('myapp').constant('angularMomentConfig', {
    timezone: 'Name of Timezone' // e.g. 'Europe/London'
});

Remember to include moment-timezone.js v0.3.0 or greater in your project, otherwise the custom timezone functionality will not be available. You will also need to include a timezone data file that you can create using the Timezone Data Builder or simply download from here.

Accessing moment() in your JavaScript

If you wish to use moment() in your services, controllers, or directives, simply inject the moment variable into the constructor.

License

Released under the terms of the MIT License.

angular-moment's People

Contributors

aalexgabi avatar ajhodges avatar alippai avatar almogbaku avatar bbodenmiller avatar dalen avatar derekdomino avatar diegozoracky avatar efolio avatar erichbschulz avatar felippenardi avatar gabrielstuff avatar jblashka avatar jc1arke avatar jniles avatar just-boris avatar jwanglof avatar kaililleby avatar kayhadrin avatar kitbrennan90 avatar kylecannon avatar nicholasruggeri avatar omerbasar avatar ondram avatar otang avatar pipo02mix avatar stackia avatar urish avatar vosi avatar wallin 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

angular-moment's Issues

Issue using angular-moment and requirejs

Because momentjs lib can check if the define function (from requirejs) exists and in this case create a module for requirejs, the moment variable is not global and so cannot be accessible using $window.moment so this create some execution errors.

One fix actually is to load requirejs after momentjs but I think this should be fix

momentjs: v2.5.1
angular-moment: v0.6.2

customize output

I was trying to achieve an output like this: <b>7</b> days ago, 7 <small>days ago</small> or anything similar to be able to apply some css. After a look at the source I couldn't find a way. Would you point a way to do this? Is it possible to do without modifying your code, just re-declaring the directive?

My current code is:
<span class="adate" am-time-ago="history.date"></span>
also note that where I added days ago could've been seconds ago, months ago, etc

Invalid date

For null or empty string json values, angular-moment is returning "Invalid date". Is it possible to return an empty string, instead. Thanks!

{{r.updated_datetime | amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a'}}

am-time-ago and time zone

Is it possible to set time zone for am-time-ago? I tried with

.constant('angularMomentConfig', {
timezone: 'Etc/UTC'
});

and also included moment-timezone.js and generated zones but seems it is ignored.

Angular can't find Moment when using uglify

Hi,

So, I'm in a grunt based project and I have, among other tasks, a ngmin then a uglify tasks. I had no problem until I started using MomentJs via angular-moment and I got message like:

Unknown provider: cProvider <- c <- Moment <- Search
[…]

Without uglify, it works. Looking at the sources ngmin generates, I find as expected stuff like that:

app.factory('Search', [
  '$http',
  '$locale',
  'SETTINGS',
  'Moment',
  function ($http, $locale, SETTINGS, Moment) {

[…]

So I guess ngmin is not involved in this. And I have no trouble with any other provider than Moment, that's what brings me here.

Any idea? Am I missing something?

more preprocessors: Unix Timestamp / Date.now()

In my angular app I'm using Linux Timestamps generated by Date.now().

Is it possible to add the adequate preprocessor for this? (simply /1000 to existing unix preprocessor). moment.js itself supports both as well.

Best,
Robert

Protractor never synchronizes on pages using am-time-ago directive

The am-time-ago directive uses the $timeout service to automatically update the text as time passes. This causes protractor tests to fail, as there is always a pending $timeout and thus it never manages to synchronize. For more information about protractor synchronization, see [https://github.com/angular/protractor/issues/49] .

In order to fix this issue, we simply need to replace the $timeout calls with vanilla $window.setTimeout().

Preprocess set in configuration not used by filters

Configuring a preprocessor like this:

 angular.module('myapp').constant('angularMomentConfig', { preprocess: 'utc' });

has no effect on filtered values. The fix is to add one line to the preprocessDate() method:

this.preprocessDate = function (value, preprocess, format) {
    preprocess = preprocess || angularMomentConfig.preprocess; // THIS LINE MISSING
    if (this.preprocessors[preprocess]) {
        preprocess = preprocess || angularMomentConfig.preprocess;
        ...

Moment() constructor with non-ISO string is deprecated

When using an angular-moment filter such as amDateFormat, a deprecation warning is logged:

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.

The following lines plead guilty:

Please add index.js or "main" property to package.json

In order to use with browserify, I need to use require('angular-moment/angular-moment');. Ideally, this would be require('angular-moment');

Please add "main": "./angular-moment.js" to package.json or add an index.js containing the following:

'use strict';
module.exports = require('./angular-moment');

Moment change language is deprecated

Current Code:
myapp.run(function(amMoment) {
amMoment.changeLanguage('de');
});
Warning on console of moment.js:
Deprecation warning: moment.lang is deprecated. Use moment.locale instead.

Also language files were moved to the "locale" folder. So I get an error 404 of my request to
GET http://localhost:9001/bower_components/moment/lang/de.js

Solution:
Add amMoment.changeLocale('de');
Access the locale settings of moment.

Workarround:
(to be tested):
myapp.run(function(amMoment) {
amMoment.moment.locale("de").format('LLL');
});

** Source: **

Changing the language with an extra parameter

Moment writes in their doc:

As of version 2.0.0, a language key can be passed as the third parameter to moment() and moment.utc().

moment('2012 juillet', 'YYYY MMM', 'fr');
moment('2012 July', 'YYYY MMM', 'en');

This would be a nice addition...

Changing the configured language

Instructions on changing the language is insufficient, please update the docs.

I'm using such a moment js file that as in-built language files. How do I change the language to be more specific?

Add 'bind once' for am-time-ago

As I am using angular-moment on mobile apps, so I don't want to update the time-ago unless users intentionally refresh the view in order to improve performance.

angularMoment is not available

While trying to add angularMoment as a dependency as shown in README.md, Angular says it does not know such module. While it seems to know angular-momentjs.

Timezone issues

I followed the example in the README and ran into a problem.

I'm trying to get my UTC stored times in presented in a 'Europe/Berlin' timezone.

These are the libraries I'm using:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.0.3/moment-timezone.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-moment/0.6.2/angular-moment.min.js"></script>

After including the 'angularMoment' into my app dependencies, {{ event.start_time | amCalendar }} works just fine, event.start_time is "2014-05-14T14:00:00.000Z"

However when I try to specify the timezone like this:

angular.module('app').constant('angularMomentConfig', {
  preprocess: 'utc',
  timezone: 'Europe/Berlin'
});

I get the following error:

Can't interpolate:  {{ event.start_time | amCalendar }}
TypeError: Cannot call method 'rule' of undefined

What am I doing wrong?

Thanks!

Angular end-to-end testing issue

Hey, thanks for creating this little integration. It's working great on the site and unit testing...until I run my e2e test using angular scenario. As soon as I use the am-time-ago directive the tests just hang.

<span am-time-ago="login.time"></span>

I wondered if you might have any ideas as to why this would happen or how I might work around it.

Thanks again,
Dehru

Support for i18n

moment.js has a nice support for i18n translation.

Is there a way to switch the language used by angular-moment globally?

In vanilla moment.js it's just a moment.lang(String); call... shouldn't be so difficult, what do you think?

am-time-ago directive does not honor configured timezone

A now() date with no timezone is displayed as is when used with
the am-time-ago directive, even if I have configured the timezone support,

ex: if I create a date with 14:00 without timezone, and local time is 12:00, it will show "in 4 hours" even if I configure the timezone to have -4 hours, I would expect tho show
"just now"...

looking at the code, it seems as if timezone offsetting is not done for this directive,
not sure if this is by design though.

I configured the timezone support :

https://github.com/urish/angular-moment#time-zone-support

.constant('angularMomentConfig', {
   preprocess: 'unix', // optional
   timezone: 'Europe/London' // optional
});

Timezone Not Working on Timeago Directive

I'm not sure if this is a bug or if I'm missing something, or if it just hasn't been implemented yet. When registering the timezone in the angularMomentConfig constant the timezone isn't effective in the Timeago Directive. The preprocess variable does take effect, although the timezone variable does not. This is how I'm declaring it:

angular.module('myAppNameHere').constant('angularMomentConfig', {
    timezone: 'America/Los_Angeles'
});

Any ideas?? Thanks.

am-time-ago as filter

This directive may be used only if somebody want to place the message into html element.
But sometimes may need to assign this message to attribute, for example, to title.
Have you some ideas about it?

Adding duration filtering

Hi !
I'm glad you've done this directive. This is very nice.

I was wondering how do you plan to add the duration method ? I have a number of millisecondes that I'd like to show in hours / minutes, this would use the duraction() from momentjs + humanize.

Should I add a filter, such as :

{{data.duration | amDurationFormat}}

Thanks !

ISO 8601 parsing is broken

#2 breaks the ability to use any of the other date formats Moment.js supports.

This date is a type of ISO 8601 datestamp. Handling of such should therefore be handed off to Moment.js itself, that way, both of these work:

moment('2013-05-28T01:52:29+0000').format('LLL'); // ==> "May 28 2013 11:52 AM"
moment('2010-03-15 10:30:00').format('LLL'); // ==> "March 15 2010 10:30 AM"

License is unclear

bower.json says MIT, readme.md says Apache 2.0.

Could you please clarify?

angular-moment on Bower?

there is some expectation of publication on Bower?

although the file bower.json, the project does not appear in searches

sorry my english

moment.js version on bower.json

Is there any specific reason to lock moment.js to 2.8.0 on bower.json dependencies?
I think you should leave it open to minor updates (bugfixes), changing:
moment": ">=2.0.0 <2.8.0"
to
moment": ">=2.0.0 <2.8.x"

Raises "module is undefined"

When running on the latest angular-moment. moment-timezone is declared as a dependency. moment-timezone's bower.json declares index.js (https://github.com/moment/moment-timezone/blob/27a88581c0d44c557d5122cde9946043fa1da94d/index.js) as its main entry point. This file depends on a module loading system to be present, which is not declared as a dependency of moment-timezone, moment or angular-moment. The result is an exception for module being undefined. Related: moment/moment-timezone#59

Not able to convert java timestamp values to "x minutes ago" format

Hi,

I am getting java timestamp in json object and i want to convert that to "x min ago" format but using this lib, i am not able to do that.

value being passed to $scope.watch is undefined but when i print the value, it has timestamp.

here is an example:
posted {{question.postDate}}

first expression prints the value "2013-08-16T21:21:39.000Z".

Whats wrong here?

Thanks,
Aashu

unknow amMoment provider

unknow amMoment provider, amMoment is a service, dont provider, fixed th documentation, please.

amCalendar test cases failing

PhantomJS 1.9.7 (Mac OS X) module angularMoment amCalendar filter should apply the "unix" preprocessor if angularMomentConfig.preprocess is set to "unix" and no preprocessor is given FAILED
    Expected '01/01/1970' to be '01/02/1970'.
    Error: Expected '01/01/1970' to be '01/02/1970'.
        at /Users/gregz/Projects/angular-moment/tests.js:389
PhantomJS 1.9.7 (Mac OS X) module angularMoment amCalendar filter should ignore the default preprocessor if we explicity give it null in the second argument FAILED
    Expected '12/31/1969' to be '01/01/1970'.
    Error: Expected '12/31/1969' to be '01/01/1970'.
        at /Users/gregz/Projects/angular-moment/tests.js:394
PhantomJS 1.9.7 (Mac OS X) module angularMoment amCalendar filter should gracefully handle the case where timezone is given but moment-timezone is not loaded FAILED
    Expected '01/21/2012' to be '01/22/2012'.
    Error: Expected '01/21/2012' to be '01/22/2012'.
        at /Users/gregz/Projects/angular-moment/tests.js:402

Simply Not Working

I have tried to implement this and it simply doesn't produce any results. I don't receive any errors in the console, etc.

In module definition, I have added the directive

'angularMoment'

In controller, I add:

$scope.dob = new Date()

In view, I have:

Not sure what else needs to be added?

With setting a `title` attribute mayhaps

I'm currently using angular-moment like this:

<time ng-if="event.archive_time" title="{{ formatDate(event.archive_time) }}" am-time-ago="event.archive_time"></time>

It works great because it displays it as "2 hours ago" but when you hover over the text you get the full, accurate, description of the date.

Could this be something built into angular-moment perhaps?

optional attribute amWithSuffix

In our application we have different use cases for this great directive. In one case we need a suffix and in other parts of application we dont. It would be great if options like this would be optional. We could pass the option with an attribute like this:

DOM:

<span am-time-ago="entity.createdAt" am-without-suffix="true"></span>

Directive:

return function (scope, element, attr) {
    var activeTimeout = null;
    var currentValue;
    var currentFormat;
    var wihoutSuffix = attr.amWithoutSuffix || false;
    ...
    function updateTime(momentInstance) {
        element.text(momentInstance.fromNow(wihoutSuffix));

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.