ng-value not working properly


In angular 1 ng-value don't work properly with ng-required. When the following code is run it displays that "The input field cannot be empty" Although it contains the value of "John". When some other value is entered or something is removed from the input field, then the required sentence disappears.

Anybody knows how to solve this?

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="">

<form name="myForm">

Click here to make the input field required:

<div ng-app="" ng-init="firstName='John'">

<input name="myInput" ng-model="myInput" ng-value="firstName" ng-required="true">

<h1 ng-if="!myForm.myInput.$valid">The input field cannot be empty</h1>

</form>

</body>
</html>

It's because you're using myInput for ng-model which is undefined when the form initializes. If you ng-init the ng-model value, you will get your expected behavior (as "John" will be in the model when the form initializes):

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="">

<form name="myForm">

Click here to make the input field required:

<div ng-app="" ng-init="firstName='John'">

<input name="myInput" ng-model="firstName" ng-value="firstName" ng-required="true">

<h1 ng-if="!myForm.myInput.$valid">The input field cannot be empty</h1>

</form>

</body>
</html>