0

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?

4
  • could you provide a fiddle or equivalent? Commented Feb 20, 2015 at 12:57
  • Works fine in a fiddle: jsfiddle.net/hpeinar/5gj9y6k4/2 Commented Feb 20, 2015 at 13:00
  • @HenrikPeinar. In fact no it doesn't. If you look at the console you will see that the fiddle also only calls the foo method once for each item in the list. Commented Feb 20, 2015 at 13:08
  • 1
    Please see my answer and updated fiddle. I misleadingly only checked for the default radio input selection Commented Feb 20, 2015 at 13:09

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

That is brilliant. This fixed issue 2 for me but issue 1 is not fixed yet. I simply cannot get the first item in the dropdown to be selected by default. Any idea why? I will still mark this as answer though.
This weird though because in the fiddle the default selection is working fine, even if the selectedFoo variable is changed. It checks the radio button which value is already in the "ng-model".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.