Sachin Kainth
Sachin Kainth

Reputation: 46740

AngularJs: Radio Button Not Selected By Default

I have the following snippet in my directive template

'<li ng-repeat="f in foos">' +
'<input type="radio" ng-change="foo(f.key)" ng-model="selectedFoo" name="foos" id="{{f.key}}" value="{{f.key}}">{{f.value}}</input>' +
'</li>' +

In my link method I have

scope.foos = [
                    { key: 'a', value: 'A', checked: true, symbol: 'a' },
                    { key: 'b', value: 'B', symbol: 'b' },
                    { key: 'c', value: 'C', symbol: 'c' }
                ];
scope.selectedFoo = "a";

I have method foo that does this

scope.foo = function(selectedValue) {
                    scope.selectedMatchType = selectedValue;
                };

There are two problems that I am facing

  1. Even though I have set ng-model to selectedFoo, the first element in the dropdown is not set by default when the radio buttons get rendered.
  2. The method foo is only called once for each element in the list. So, for example if I click on A, foo is called, if I then click on B, foo is called, if I click on A again foo is not called, but if I then click on C, foo is calle.

What is wrong here?

Upvotes: 0

Views: 502

Answers (1)

Henrik Peinar
Henrik Peinar

Reputation: 2201

Please note that ng-repeat creates it's own scope for every template which means you'll have to use $parent in ng-model for the input.

ng-model="$parent.selectedFoo"

Also a working fiddle with your code example: http://jsfiddle.net/hpeinar/5gj9y6k4/

Upvotes: 2

Related Questions