2017-09-26 59 views
2

在使用ng-required时,角度1的ng值无法正常工作。当运行以下代码时,会显示“输入字段不能为空” 尽管它包含“John”的值。 当输入一些其他值或从输入栏中删除某些内容时,所需句子消失。ng值无法正常工作

任何人都知道如何解决这个问题?

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

回答

2

这是因为你使用myInputng-model这是undefined当窗体初始化。如果NG-INIT的NG-模型值,你会得到你预期的行为(如“约翰”将在模型时的形式初始化):

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