angularjs : nggrid with Datetime or epoch datetime


I am currently working with Angularjs and NG-Grid plugin from the same angularjs team. I was getting issue in displaying “DateTime” field properly into the grid because, I was getting Epoch datetime format back to client JS from server.

e.g /Date(342342343242)/   Something like this we known as Epoch Datetime.

Now I was looking on google and found this really helpful article from “Christiaan Baes” http://blogs.lessthandot.com/index.php/webdev/uidevelopment/javascript/angularjs-and-ng-grid/

Formatting the date

First we need to add moment.js import to our index.html.

Then we need to add a filter to our app.js.

Like this.

Javascript

angular.module('plantsapp', ['ngGrid']).   config(['$routeProvider', function ($routeProvider) {       $routeProvider.           when('/plants', { templateUrl: 'partials/plants.html', controller: PlantsController }).           when('/plants/:Id', { templateUrl: 'partials/plant.html', controller: PlantController }).           otherwise({ redirectTo: '/plants' });   }]).filter('moment', function () {       return function (dateString, format) {           return moment(dateString).format(format);       };   });;

And now we need to change our controller so that we can add this filter to our column definition for DateAdded.

Like this.

Javascript

function PlantsController($scope, $http) {     $scope.plants = [];     $scope.myOptions = {         data: 'plants',         columnDefs: [                         {field:'Id', displayName:'Id'},                         {field:'Name', displayName:'Name'},                         { field: 'Genus', displayName: 'Genus' },                         { field: 'DateAdded', displayName: 'Date added', cellFilter:"moment:'DD/MM/YYYY h:m'" }         ]     };     $http.get('http://localhost:59025/plants').success(function (thisdata) {         $scope.plants = thisdata;     });
}

Of course we could set our fofrmat straight in the filter and and then just use the moment filter.

For this we just need to change the filter to this.

Javascript

return moment(dateString).format('DD/MM/YYYY h:m');

and the columndefinition then becomes this.

Javascript

{ field: 'DateAdded', displayName: 'Date added', cellFilter:"moment" }

And tada!!!!

Happy Coding… Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s