问题
I need to generate a list of radio button inputs from a List
, and to link the <label for="xx">
tag to the <input>
, each needs its own id.
But it seems Dart cannot bind to an id attribute:
<div id="{{s}}">
<p id="text">{{s}}</p> <!-- Works as expected -->
</div>
The above results in the error:
Error: line 40 pos 22: illegal use of class name 'DivElement' autogenerated_html.DivElement __{{s}};
So my question is: Can Dart bind to an id attribute, and if so how?
And an alternative question: Is there another way to use web_ui generate a list of radio button inputs with labels?
回答1:
As your example shows, the web ui compiler uses IDs in a very special way. The compiler assumes they are string constants, and uses them to generate fields and local variable names and also to query for the element in the generated code.
I'd say this is a bug/feature request that should be addressed somehow in web_ui. You can follow progress on this issue here: https://github.com/dart-lang/web-ui/issues/284
回答2:
I'll try to answer your alternate question. You can create a pair of elements - a radio button inputs and labels - and attach to the DOM as necessary. To create, 'male' and 'female' buttons, you could do this:
var button1 = new RadioButtonInputElement();
button1.name = "sex";
button1.value = "male";
button1.attributes['id'] = "sex_male";
var button1_label = new LabelElement();
button1_label.attributes['for'] = button1.id;
button1_label.text="Male";
var button2 = new RadioButtonInputElement();
button2.name = "sex";
button2.value = "female";
button2.attributes['id'] = "sex_female";
var button2_label = new LabelElement();
button2_label.attributes['for'] = button2.id;
button2_label.text="Female";
use new RadioButtonInputElement()
to create a radio input; use new LabelElement()
to create the accompanying label.
This code isn't particularly DRY; if you are going to generate a lot of these, you might want to refactor it into a function. Something like this:
List createButtonWithLabel(name, value) {
var button = new RadioButtonInputElement();
button.name = name;
button.value = value;
button.attributes['id'] = "${name}_${value}";
var label = new LabelElement();
label.attributes['for'] = button.id;
label.text=value.toUpperCase();
return [button, label];
}
and then use it like this:
var form = new FormElement();
form.nodes.addAll(createButtonWithLabel('sex', 'male'));
form.nodes.addAll(createButtonWithLabel('sex', 'female'));
query('body').nodes.add(form);
This should give you a form with 2 radio buttons.
来源:https://stackoverflow.com/questions/14038618/can-dart-bind-to-id-attribute