javascript - Angular radio validation in ng-repeat -
i'm trying create form valid if radio button selected. radio button part of grouping user can take one. i'm assigning required
attribute radio buttons using function in controller, , seems causing issues validation. think it's sort of scope problem can't figure out.
here's jsfiddle showing problem: http://jsfiddle.net/flyingl123/x27nv8fq/5/
you can see radio inputs correctly have required
attribute assigned them, if user doesn't select option, form still validates , submits.
here's 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 invalid</p> {{ selectedoption }} </form> </div>
and 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 , submitted'); } $scope.required = function(){ if(!$scope.selectedoption.id){ homecoming true; } homecoming false; } }]);
why form considered valid though required
radio input not selected?
there 2 issues noticed:
1) $scope.selectedoption (as mentioned) 2) $scope.required function unnecessary far can tell. should set required true on inputs - angular knows via name attribute 1 of inputs needs checked.
you can see in action here - 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 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 , submitted'); } }]);
javascript angularjs validation
No comments:
Post a Comment