Extranion
Extranion

Reputation: 608

Angular form validation is invalid after changing the value in the scope var

Reproduce the problem

  1. Open plunker in Firefox
  2. Type "oEfeowjewfj"

You see that myForm.input.$valid is false, thats the expected result. After that we continue:

  1. push the button "SetValue"

Now you see that the value is changed, but myForm.input.$valid is still false

Question

How can I set the time through code in a form and as a result the myForm.input.$valid is true?

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>

Upvotes: 2

Views: 744

Answers (2)

abdelouahed touimi
abdelouahed touimi

Reputation: 76

I suggest you the angular API Documentation: https://docs.angularjs.org/api/ng/input/input%5Btime%5D

you will need to change setValue function :

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

you will have to set the ng-model to a valide javascript date object.

Upvotes: 3

capgeti
capgeti

Reputation: 145

model object must be always a date object

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

see here

Upvotes: 1

Related Questions