2016-03-08 72 views
1

假设我有一个<input>字段和type='date'属性。未触及时,显示日期为mm/dd/yyyy。有没有什么办法,使用AngularJS的ng-blur指令来清除字段回到这种状态,当用户输入输入,说03/21/2016,删除其中一个领域(即03/dd/2016),然后点击外部('模糊')的领域?如何清除模糊处的无效日期字段? (AngularJS)

+0

设置范围变量'ng-model'绑定到一个新的'Date()'? –

+0

新的日期对象具有当前日期的值 – pv93

+1

奇怪的是,您似乎必须通过本地JS或jQuery重置它:​​'$(“input”).val(null);' - 请参阅https:/ /jsbin.com/bivuqitefi/1/edit?html,js,output –

回答

0

NG-模糊,

在HTML

<input type="date" ng-model="date" ng-blur="blured()" /> 

在你的控制器

$scope.blured = function() 
{ 
    // check the date 
    // if invalid 
    $scope.date = null; 
} 

还看到:

https://docs.angularjs.org/api/ng/directive/ngBlur

+0

这并不具有预期的效果,因为尽管模型设置为null,但输入字段视图仍显示无效日期(即02/mm/2017)。我需要一种方法来清除视图以及模型。如果您要问,无效输入上的$ viewValue的值已经设置为空字符串,所以操作它什么也不做。 – pv93

+0

是[this](http://jsfiddle.net/nzPJD/252/)所需的效果? –

0

在HTML

<input type="date" ng-model="date" ng-blur="blured(date,$event)" /> 

在您的JS

$scope.blured= function (inputdate, e) { 
      if (!e.ctrlKey && !e.metaKey && (e.keyCode == 32 || e.keyCode > 46)) 
       doFormat(e.target); 
      if (e.target.value.length == 10) { 
       $scope.IsValidDate(1, e.target.value); 
      } 
     } 

     //id is used to check which date control 
     //method is used to validate entered date in MM/dd/yyyy format 
     $scope.IsValidDate = function (id, dateValue) { 
      var formats = ['MM/DD/YYYY'] 
      if (!moment(dateValue, formats).isValid()) { 
       if (id == 1) { 
        $scope.date = null; 
       } 
      } 
     } 

希望这对你的工作,它为我工作。

相关问题