AngularJS required radio buttons needs two click events to be valid

前端 未结 8 2013
庸人自扰
庸人自扰 2020-12-15 19:43

I have a very simple form where a radio button is required to be selected in order for a form to be valid. The radio buttons are generated by ngRepeat.

相关标签:
8条回答
  • 2020-12-15 19:54

    Try adding the ng-click attribute to your radio button input.

    Credit to Manny D for noting this first. Yes, this is a little hackish, but it works. E.g.,

    <input type="radio" 
           name="groupName"  
           ng-model="editObject.Property"                             
           ng-value="someValue"
           ng-click />
    
    0 讨论(0)
  • 2020-12-15 19:57

    I had this problem because a colleague had copied the radio buttons in the same page and hidden them for temporary reference, so duplicate radio inputs with the same name

    0 讨论(0)
  • 2020-12-15 19:57

    Some times the $digest cycle dosen't $apply(fn) because you have two o more instances. For fix this you need $apply this trick manually, so put this in your directives:

    angular.('myApp',[])
    .directive('ngRadioExtend', ['$rootScope', function($rootScope){
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, iElm, iAttrs, controller) {
                    iElm.bind('click', function(){
                        $rootScope.$$phase || $rootScope.$apply()
                    });
                }
            };
        }])
    

    and use it as:

    <input type="radio" name="input_name" ng-model="some" value="F" ng-required="true" ng-radio-extend>
    
    <input type="radio" name="input_name" ng-model="some" value="M" ng-required="true" ng-radio-extend>
    

    DONE it's the correct way!

    0 讨论(0)
  • 2020-12-15 19:58

    All the other solutions are work-arounds: All you have to do is remove the name attribute, when you use the ng-model attribute you don't need it and they conflict.

    Specifying the name causes Angular to get confused because it changes the value once for the angular model and another time for the form element name.

    0 讨论(0)
  • 2020-12-15 20:12

    The problem of the scope not getting updated still occurs in 1.1.5

    A simple work around is to just add <span ng-show="false"> {{name}} </span>

    Fiddle: http://jsfiddle.net/jonyschak/xaQJH/

    0 讨论(0)
  • 2020-12-15 20:14

    The reason why this is breaking - is because you're setting all radio boxes to be required. As a result, depending on how you write it - angularjs is saying it's invalid because not all have been selected at some point.

    The way around this is to do something like the following:

    Using checkboxes and required with AngularJS

    (check the 1st and 2nd answers). This will resolve your problem.

    0 讨论(0)
提交回复
热议问题