简体   繁体   English

AngularJs:默认未选中单选按钮

[英]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 我有这样做的方法foo

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. 即使我已将ng-model设置为selectedFoo,当呈现单选按钮时,默认情况下也不会设置下拉列表中的第一个元素。
  2. The method foo is only called once for each element in the list. 对于列表中的每个元素,仅对方法foo调用一次。 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. 因此,例如,如果我单击A,则调用foo,如果我单击B,则调用foo,如果再次单击A,则不调用foo,但是如果我再单击C,则调用foo。

What is wrong here? 怎么了

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-repeat会为每个模板创建自己的作用域,这意味着您必须在ng-model中使用$ parent进行输入。

ng-model="$parent.selectedFoo"

Also a working fiddle with your code example: http://jsfiddle.net/hpeinar/5gj9y6k4/ 还可与您的代码示例配合使用: http : //jsfiddle.net/hpeinar/5gj9y6k4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM