Donal
Donal

Reputation: 32713

Angular - unable to get selected ng-repeated radio button using ng-submit

I might be missing something really simple here - but if I use ng-repeat to create a bunch of radio buttons - I cannot get the selected one using ng-submit.

The controller simply attaches an array of options to the scope.

The markup simply creates a bunch of radio buttons with ng-repeat within a form. It uses ng-submit to capture the submit event. Click 'Run code snippet' below to see the 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>

Upvotes: 2

Views: 1106

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

You ng-repeat div should be using ng-model="$parent.selectedoption"

Reason

ng-repeat creates a new child scope every time, as you are declaring new ng-model inside ng-repeat will be added into the ng-repeat scope(child), this child scope has been created on each iteration by ng-repeat. As you want to create a scope variable to the parent scope, so you need to use $parent variable that will point the 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>

Demo Fiddle

Update

Other good way to avoid this sort of $parent annotation is by using object annotation, that will do follow the scope prototypal inheritance. Only thing you need to do is define one scope variable in your controller like $scope.selected = { option: '' } then while using it on html you could refer it as selected.option directly no need to use $parent for parent scope reference.

Demo Fiddle

Upvotes: 2

Related Questions