0

I have an array with options where I want the user to be able to choose one option.

This are my options:

 $scope.licenses = [...]

This is the selected option:

 $scope.selectedLicense = $scope.licenses[0];

And in my markup I have:

    <ul>
        <li ng-repeat="lic in licenses">
            <input type="radio" ng-model="selectedLicense" value="lic"></input>
                {{lic.nrOfLicenses}}
        </li>
    </ul>

But no radiobutton is selected at start.

Fiddle: http://jsfiddle.net/HB7LU/9765/

What am I doing wrong?

Joe
  • 4,274
  • 32
  • 95
  • 175

2 Answers2

1

You need to use the ng-value directive instead of value, this lets you use your scope object.

<input type="radio" name="license" ng-model="selectedLicense" ng-value="lic"></input>

http://jsfiddle.net/2kqp2v46/

Simon Staton
  • 4,345
  • 4
  • 27
  • 49
1

in ng-repeat directive creates child scope for each and every iteration

check the documentation

Each template instance gets its own scope

so when repeating there is a scope variable called selectedLicense in each and every child scope. so your $scope.selectedLicense not bind to the radio buttons as expected.

here you can use prototypical inheritance, here is the great answer for what is JavaScript Prototypal Inheritance

$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0].nrOfLicenses;

<input type="radio" ng-model="x.selectedLicense" ng-value="lic.nrOfLicenses"></input>
// here angular search the `selectedLicense` in the child scope and then it will search the x object in parent scope after it detect there is no `selectedLicense` in the child scope.

here is the demo Fiddle


in the above example radio buttons are bind to the nrOfLicenses property in the object.

if you want to bind the radio to the whole object, then follow this

$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0];

<input type="radio" ng-model="x.selectedLicense" ng-value="lic"></input>

here is the demo Fiddle

Community
  • 1
  • 1
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92