2014-11-06 27 views
0

我試圖創建一個有效的表單,如果選中一個單選按鈕。單選按鈕是用戶可以從中選擇一個組的一部分。我使用我的控制器中的函數將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無線電輸入?

回答

0

看起來像問題是我正在初始化$scope.selectedOption{},而不是讓它不確定。我猜測,由於空對象是「真理」,Angular認爲它是有效的。從代碼中刪除這似乎已經解決了問題。

1

有2個問題,我注意到:

1)$ scope.selectedOption(如你所提到的) 2)$ scope.required功能是不必要的,因爲據我可以告訴。你只需要在這些輸入上設置true就可以了 - Angular通過name屬性知道只有一個輸入需要檢查。

您可以在這裏的行動看到它 - http://jsfiddle.net/x27nv8fq/6/

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="selectedOption" 
       ng-required="true" /> 
      {{ option.value }} 
     </div> 
     <button type="submit">Submit</button> 
     <p ng-show="testForm.testInput.$invalid">Form is invalid</p> 
     {{ selectedOption }} 
    </form> 
</div> 

的Javascript

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'); 
    } 
}]);