how to moment().fromNow() in angular-moment?

2.2k views Asked by At

How can I do this moment().fromNow() in angular-moment?

<div class="date pull-right"> {{ a.Alert.date }}...</div>

How can I apply fromNow() to my variable "a.Alert.date"?

In momentjs I can do this:

moment().fromNow()
"a few seconds ago"
moment('2016-12-11').fromNow()
"23 days ago"

https://github.com/urish/angular-moment

2

There are 2 answers

0
VincenzoC On BEST ANSWER

You can simply use am-time-ago directive.

Here a working example:

angular.module('MyApp',['angularMoment'])
.controller('AppCtrl', function($scope) {
  $scope.a = {
    Alert: {
      date: new Date()
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.min.js"></script>

<div ng-app="MyApp" ng-controller="AppCtrl">
  <span am-time-ago="a.Alert.date"></span>
</div>

1
Anthony C On

You can do the same thing as you did in Pure JS by simply set a.Alert.date as moment Date and call fromNow in the view

angular.module('MyApp',['angularMoment'])
.controller('AppCtrl', function($scope, moment) {
  $scope.a = {
    Alert: {
      date: moment()
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.min.js"></script>

<div ng-app="MyApp" ng-controller="AppCtrl">
  <div class="date pull-right"> {{ a.Alert.date.fromNow() }}...</div>
</div>