Use jQuery timeago or momentjs and AngularJS together

前端 未结 4 1670
迷失自我
迷失自我 2020-12-23 12:48

I want to use timeago plugin to make dates look nicer. The problem is that these dates are fetched via AngularJS from the REST dynamically. So, when I attach this jQuery plu

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 13:52

    I would use momentjs - http://momentjs.com/ - it has no dependencies.

    Then you can just create a filter called 'timeAgo' or 'fromNow'. You should probably call it fromNow because that's what momentjs calls it:

    angular.module('myApp').filter('fromNow', function() {
      return function(date) {
        return moment(date).fromNow();
      }
    });
    

    Then you would just use simple data binding in your view:

    Pizza arrives {{pizzaArrivalDate | fromNow}}

    If you really wanted to use the jQuery plugin, you would probably have to write a directive. But that way of doing it is bad because it links your data to a DOM element. The way I put above seperates data from DOM which is the angular way. And it's pretty :-D

提交回复
热议问题