【问题标题】:how to get current and previous date in angular?如何以角度获取当前和上一个日期?
【发布时间】:2016-01-29 02:34:36
【问题描述】:

我在角度使用日期选择器..它工作正常。但是当用户输入“t”或“T”时我需要它显示当前或今天的日期..如果用户输入“t-1”..it显示昨天的日期......当用户输入“t+1”时,它显示明天的日期。

这是我的代码 http://plnkr.co/edit/UnxLAHmKZU15cqukKqp5?p=preview

 angular.module('app',['ui.bootstrap']).controller('cntrl',function($scope){

    $scope.open2 = function() {
    $scope.popup2.opened = true;
  };

  $scope.popup2 = {
    opened: false
  };



  }).directive('toDateCheck', function() {

    return {
      require: 'ngModel',
      link: function link(scope, element, attr, ngModel) {
        scope.$watch(attr.ngModel, function(val) {
          console.log(val)

        })
      }
    }
})

【问题讨论】:

  • 查看 JavaScript Date 类以获取当前日期
  • 我可以在从日期选择器中选择后设置日期..可以从右侧的日期选择器中选择日期

标签: angularjs angularjs-directive angularjs-scope angular-ui-router


【解决方案1】:

您想要做的是在您的指令上使用解析器。您的 $watch 没有触发的原因是它没有通过验证。试试这样的。

.directive('toDateCheck', function($browser) {

return {
  require: 'ngModel',
  link: function link(scope, element, attr, ngModelCtrl) {
    scope.$watch(attr.ngModel, function(val,l) {
      console.log(val,l);
    });

     ngModelCtrl.$parsers.unshift(function(viewValue){
         if(viewValue === 't-1'){
           var yesterday = new Date();
           yesterday.setDate(yesterday.getDate() - 1);
           // Update the textbox to show the new value
           element.val(yesterday.toLocaleDateString());
           return yesterday;
         }
         return viewValue;
     });
  }
}

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多