我試圖創建一個有效的表單,如果選中一個單選按鈕。單選按鈕是用戶可以從中選擇一個組的一部分。我使用我的控制器中的函數將required
屬性分配給單選按鈕,這似乎是導致驗證問題。我認爲這是一些範圍問題,但我無法弄清楚。ng-repeat中的角度無線電驗證
這裏的顯示問題的jsfiddle:http://jsfiddle.net/flyingL123/x27nv8fq/5/
你可以看到,無線輸入正確分配給他們的required
屬性,但即使用戶不選擇一個選項,形式還是驗證並提交。
這裏的HTML:
<div ng-app="test" ng-controller="TestController">
<form name="testForm" ng-submit="testForm.$valid && submitForm()" novalidate>
<div ng-repeat="option in options">
<input type="radio" name="testInput"
ng-value="option"
ng-model="$parent.selectedOption"
ng-required="required()" />
{{ option.value }}
</div>
<button type="submit">Submit</button>
<p ng-show="testForm.testInput.$invalid">Form is invalid</p>
{{ selectedOption }}
</form>
</div>
而且JS:
var test = angular.module('test', []);
test.controller('TestController', ['$scope', function($scope){
$scope.options = [{id: '0', value: 'blue'}, {id: 1, value: 'green'}]
$scope.selectedOption = {};
$scope.submitForm = function(){
alert('Form valid and submitted');
}
$scope.required = function(){
if(!$scope.selectedOption.id){
return true;
}
return false;
}
}]);
爲什麼形式視爲有效,即使沒有選擇required
無線電輸入?