Reputation: 127
I have dates in this format in my json "26 Feb 2015 00:00:00" which I would like to be converted to day of the week ie Tue This seems straightforward using momentjs but my question is how to call the momentjs format() method inside html vs. inside the <script> I guess I can create a new json string inside the script but would like to avoid that
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test" ng-controller="test">
<table>
<tr><th>day</th><th>value</th></tr>
<tr ng-repeat="tsval in data['key']">
<td>{{tsval.timestamp }}</td>
<td>{{ tsval.val }}</td>
</tr>
</table>
</body>
<script>
angular.module('test', []).controller('test', function($scope) {
$scope.data = {
'key':[
{
'timestamp':'26 Feb 2015 00:00:00 GMT',
'val':'v1'
},
{
'timestamp':'27 Feb 2015 00:00:00 GMT',
'val':'v2'
},
{
'timestamp':'28 Feb 2015 00:00:00 GMT',
'val':'v3'
}
]
};
});
</script>
</html>
Upvotes: 1
Views: 5219
Reputation: 43745
Here's a custom filter that wraps moment().format()
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.myDate = '28 Feb 2015 00:00:00 GMT';
})
.filter('format', function() {
return function(input, format) {
return moment(new Date(input)).format(format);
};
})
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{myDate | format:'ddd'}}</p>
</div>
You can also just use Angular's built in date
filter for this, but it doesn't like your date format, so you'd have to apply another filter to convert it to an ISO string first. If you don't need momentjs for any other reason, I'd get rid of it and just do this.
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.myDate = '28 Feb 2015 00:00:00 GMT';
})
.filter('dateToISO', function() {
return function(input) {
return new Date(input).toISOString();
};
})
;
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{myDate | dateToISO | date:'EEE'}}</p>
</div>
Upvotes: 3
Reputation: 10454
Simply add a helper function to the scope that formats the provided date as a day.
angular.module('test', []).controller('test', function($scope) {
$scope.data = {
'key': [{
'timestamp': '26 Feb 2015 00:00:00 GMT',
'val': 'v1'
}, {
'timestamp': '27 Feb 2015 00:00:00 GMT',
'val': 'v2'
}, {
'timestamp': '28 Feb 2015 00:00:00 GMT',
'val': 'v3'
}]
};
$scope.toDay = function(date) {
return moment(date).format('ddd');
};
});
And in your template, fire the helper off and pass the date as the argument.
<td>{{ toDay(tsval.timestamp) }}</td>
This renders:
day value
Wed v1
Thu v2
Fri v3
Here's a plunker
Upvotes: 1