I got a view in angularjs and I\'m just trying to display the current date(formatted). I thought something like {{Date.now() | date:\'yyyy-MM-dd\'}}
Here is the sample of your answer: http://plnkr.co/edit/MKugkgCSpdZFefSeDRi7?p=preview
<span>Date Of Birth: {{DateOfBirth | date:"dd-MM-yyyy"}}</span>
<input type="text" datepicker-popup="dd/MM/yyyy" ng-model="DateOfBirth" class="form-control" />
and then in the controller:
$scope.DateOfBirth = new Date();
Template
<span date-now="MM/dd/yyyy"></span>
Directive
.directive('dateNow', ['$filter', function($filter) {
return {
link: function( $scope, $element, $attrs) {
$element.text($filter('date')(new Date(), $attrs.dateNow));
}
};
}])
Because you can't access the Date
object direcly in a template (for an inline solution), I opteted for this Directive. It also keeps your Controllers clean and is reusable.
You can also do this with a filter if you don't want to have to attach a date object to the current scope every time you want to print the date:
.filter('currentdate',['$filter', function($filter) {
return function() {
return $filter('date')(new Date(), 'yyyy-MM-dd');
};
}])
and then in your view:
<div ng-app="myApp">
<div>{{'' | currentdate}}</div>
</div>
Well, You can do it with mustache expression ({{Date.now() | date:'dd.MM.yyyy HH:mm:ss'}}
). You just need to assign the Date object to scope where You want to evaluate this expression.
Here's jsfiddle example: jsfiddle
But don't expect it to update value automatically. This value is not watched by angular so You have to trigger digest every time You want to get it updated (by $interval for example)...which is waste of resources (and also not "recommended" in docs). Of course You can get to use of combination with directives/controllers to mess around with child scope only (it's always smaller than for example rootScope and digest will be quicker).
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
var today = new Date();
console.log($scope.cdate);
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var current_date = date+'/'+month+'/'+year;
console.log(current_date);
});
</script>