我被要求在網頁上顯示是/否單選按鈕。在初始狀態下,這些選項都未被選中。需要驗證以確保用戶選擇其中的一個。我能做到這一點使用的瀏覽器自身的表單驗證,就像這樣:使用Angular驗證單選按鈕的選擇
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-radio-input-directive-production</title>
<script src="angular.min.js"></script>
</head>
<body ng-app="radioExample">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.submitForm = function() {
alert('valid');
}
}]);
</script>
<form name="myForm" ng-submit="submitForm()" ng-controller="ExampleController" novalidate>
<input name="question" type="radio" ng-model="question" value="yes" required>Yes<br/>
<input name="question" type="radio" ng-model="question" value="no">No<br/>
<pre>myForm.question.$error = {{ myForm.question.$error | json }}</pre>
<div ng-messages="myForm.question.$error" role="alert">
<div ng-message="required">You did not enter a field</div>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
我希望能夠利用的角度,以顯示在NG-消息的驗證消息,但我在努力使它工作:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-radio-input-directive-production</title>
<script src="angular.min.js"></script>
</head>
<body ng-app="radioExample">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.submitForm = function() {
alert('valid');
}
}]);
</script>
<form name="myForm" ng-submit="submitForm()" ng-controller="ExampleController" novalidate>
<input name="question" type="radio" ng-model="question" value="yes" required>Yes<br/>
<input name="question" type="radio" ng-model="question" value="no">No<br/>
<pre>myForm.question.$error = {{ myForm.question.$error | json }}</pre>
<div ng-messages="myForm.question.$error" role="alert">
<div ng-message="required">You did not enter a field</div>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
我做錯了什麼?