Angularjs - display current date

后端 未结 11 1147
醉酒成梦
醉酒成梦 2020-12-04 08:06

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\'}}

相关标签:
11条回答
  • 2020-12-04 09:01

    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();
    
    0 讨论(0)
  • 2020-12-04 09:02

    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.

    0 讨论(0)
  • 2020-12-04 09:04

    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>
    
    0 讨论(0)
  • 2020-12-04 09:07

    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).

    0 讨论(0)
  • 2020-12-04 09:07
    <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>
    
    0 讨论(0)
提交回复
热议问题