1

我試圖在指令中包裝<input>,以便我可以處理日期驗證並將其從字符串轉換爲實際的Date對象並將Date版本保留在原始範圍內。這種互動按預期工作。但<input>元素上的ng-pattern行事不正確。無論輸入什麼,它都不會使<input>無效。ng-pattern在指令內不起作用

HTML

<pl-date date="date"></pl-date> 

JS

.directive("plDate", function (dateFilter) { 
    return { 
    restrict: 'E', 
    replace: true, 
    template: '<input id="birthDateDir" name="birthDate" type="text" ng-pattern="{{getDatePattern()}}" ng-model="dateInput">', 
    scope: { 
     date: '=' 
    }, 
    link: function (scope) { 
     scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy'); 

     scope.$watch('date', function (newVal) { 
      if (newVal !== scope.tmp) { 
       if (!newVal) { 
        scope.dateInput = null; 
       } else { 
        scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy'); 
       } 
      } 
     }); 

     scope.getDatePattern = function() { 
      var exp = '/'; 

      // Removed for brevity 

      exp += '/'; 

      return exp; 
     }; 

     scope.$watch('dateInput', function (newVal) { 
      if (newVal !== null) { 
       scope.date = new Date(newVal); 
       scope.tmp = scope.date; 
      } 
     }); 
    } 
}; 

的jsfiddle這裏:https://jsfiddle.net/e5qu5rgy/1/

任何幫助就大家大大感謝!

回答

0

所以看起來這個問題可以通過改變link功能的指令是一個controller功能,而不是固定的,如下

.directive("plDate", function (dateFilter) { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<input id="birthDateDir" name="birthDate" class="formField" type="text" ng-pattern="{{getDatePattern()}}" ng-model="dateInput">', 
     scope: { 
      date: '=' 
     }, 
     controller: function ($scope, $element, $attrs) { 
      $scope.dateInput = dateFilter($scope.date, 'MM/dd/yyyy'); 

      $scope.$watch('date', function (newVal) { 
       if (newVal !== $scope.tmp) { 
        if (!newVal) { 
         $scope.dateInput = null; 
        } else if (newVal.toString() !== "Invalid Date") { 
         $scope.dateInput = dateFilter($scope.date, 'MM/dd/yyyy'); 
        } 
       } 
      }); 

      $scope.getDatePattern = function() { 
       var exp = '/'; 

       // Months with 31 days 
       exp += '^(0?[13578]|1[02])[\/.](0?[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2}$'; 

       //Months with 30 days 
       exp += '|^(0?[469]|11)[\/.](0?[1-9]|[12][0-9]|30)[\/.](18|19|20)[0-9]{2}$'; 

       // February in a normal year 
       exp += '|^(0?2)[\/.](0?[1-9]|1[0-9]|2[0-8])[\/.](18|19|20)[0-9]{2}$'; 

       // February in a leap year 
       exp += '|^(0?2)[\/.]29[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)$'; 

       exp += '/'; 

       return exp; 
      }; 

      $scope.$watch('dateInput', function (newVal) { 
       if (newVal !== null) { 
        $scope.date = new Date(newVal); 
        $scope.tmp = $scope.date; 
       } 
      }); 
     } 
    }; 
}); 

在投入生產之前,將controller需要切換成使用數組作爲參數來防止縮小。