2017-09-26 66 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>