2016-03-08 58 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; 
       } 
      } 
     } 

希望這對你的工作,它爲我工作。