javascript - Angular - unable to get selected ng-repeated radio button using ng-submit -
i might missing simple here - if use ng-repeat create bunch of radio buttons - cannot selected 1 using ng-submit.
the controller attaches array of options scope.
the markup creates bunch of radio buttons ng-repeat within form. uses ng-submit capture submit event. click 'run code snippet' below see issue.
angular.module('myapp', []) .controller('mycontroller', ['$scope', function($scope) { $scope.selectedoption = ""; $scope.submitcalled = ""; $scope.options=[]; $scope.options[0]={id: "option1", name: "option 1"} $scope.options[1]={id: "option2", name: "option 2"} $scope.options[2]={id: "option3", name: "option 3"} $scope.options[3]={id: "option4", name: "option 4"} $scope.submitform = function() { console.log($scope.selectedoption); $scope.submitcalled = "submit called " + $scope.selectedoption; }; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp"> <form ng-submit="submitform()" ng-controller="mycontroller"> <div ng-repeat="option in options"> <input type="radio" name="option" ng-value="option.id" ng-model="selectedoption"> <label for="radio">{{option.name}}</label> </div> <h2>{{selectedoption}}</h2> <h2>{{submitcalled}}</h2> <input type="submit" id="submit" value="submit" /> </form> </div>
you ng-repeat
div should using ng-model="$parent.selectedoption"
reason
ng-repeat
creates new child scope every time, declaring new ng-model
inside ng-repeat added ng-repeat scope(child), child scope has been created on each iteration ng-repeat
. want create scope variable parent scope, need use $parent
variable point parent scope.
<div ng-repeat="option in options"> <input type="radio" name="option" ng-value="option.id" ng-model="$parent.selectedoption"> <label for="radio">{{option.name}}</label> </div>
update
other way avoid sort of $parent
annotation using object annotation, follow scope prototypal inheritance. thing need define 1 scope variable in controller $scope.selected = { option: '' }
while using on html refer selected.option
directly no need use $parent
parent scope reference.
Comments
Post a Comment