更改范围var中的值后,角度表单验证无效

时间:2015-03-02 13:09:24

标签: angularjs forms validation input

重现问题

  1. 在Firefox中打开plunker
  2. 输入" oEfeowjewfj"
  3. 你看到myForm.input。$ valid是false,这就是预期的结果。 之后我们继续:

    1. 按下按钮" SetValue"
    2. 现在您看到值已更改,但myForm.input。$ valid仍为false

      问题

      如何在表单中设置代码的时间,因此myForm.input。$ valid是否为真?

      http://plnkr.co/edit/a4wz3bE36EbbQvftZoL5?p=preview

      <body ng-app="timeExample">
        <script>
       angular.module('timeExample', [])
         .controller('DateController', ['$scope', '$timeout', function($scope, $timeout) {
           $scope.example = {
             value: '14:00'
           };
      
           $scope.setValue = function() {
             $scope.example.value = "15:00"  
           }
         }]);
      </script>
      <form name="myForm" ng-controller="DateController as dateCtrl">
         Pick a between 8am and 5pm:
         <input type="time" id="exampleInput" name="input" ng-model="example.value"
             placeholder="HH:mm" min="08:00:00" max="17:00:00" required />
         <span class="error" ng-show="myForm.input.$error.required">
             Required!</span>
         <span class="error" ng-show="myForm.input.$error.time">
             Not a valid date!</span>
         <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
         <button data-ng-click="setValue()">SetValue</button>
      </form>
      </body>
      

2 个答案:

答案 0 :(得分:3)

我建议使用有角度的API文档:https://docs.angularjs.org/api/ng/input/input%5Btime%5D

您需要更改setValue函数:

&#13;
&#13;
$scope.setValue = function() {
  $scope.example.value = new Date(2014, 1, 3, 14, 57, 0);
}
&#13;
&#13;
&#13;

您必须将ng-model设置为valide javascript日期对象。

答案 1 :(得分:1)

模型对象必须始终是日期对象

$scope.example.value = new Date(1970, 0 ,1, 15, 0, 0);

请参阅here