ng 值无法正常工作

ng-value not working properly

在 angular 中 1 ng-value 不能与 ng-required 一起正常工作。当下面的代码是 运行 时,它显示 "The input field cannot be empty" 虽然它包含 "John" 的值。 当输入其他值或从输入字段中删除某些内容时,所需的句子就会消失。

有人知道怎么解决吗?

<!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>

这是因为您在 ng-model 中使用 myInput,当表单初始化时,它是 undefined。如果您对 ng-model 值进行 ng-init,您将获得预期的行为(因为 "John" 将在表单初始化时出现在模型中):

<!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>