我正在使用ng-repeat生成一系列单选按钮,然后尝试在选择其中一个时更新模型。但是似乎不起作用。
当单选按钮输入是硬编码的而不是由ng-repeat生成时,同样的标记正常工作。
这个可以正常工作:
<input type="radio" ng-model="lunch" value="chicken" name="lunch">
<input type="radio" ng-model="lunch" value="beef" name="lunch">
<input type="radio" ng-model="lunch" value="fish" name="lunch">
{{lunch}}
这个不行:
<input type="radio" ng-model="lunch" ng-repeat="m in meat" value="m" name="lunch">
{{lunch}}
请查看此处的 jsfiddle 示例:http://jsfiddle.net/mark_up/A2qCS/1/
感谢任何帮助。
谢谢。
$parent
的替代方案是在控制器中使用一个对象属性:$scope.selection = {lunch: 'chicken'};
,然后在 HTML 中使用:<input type="radio" ng-model="selection.lunch" ng-repeat="m in meat" ng-value="m" name="lunch"> {{selection.lunch}}
。 - Mark Rajcok$scope.selection = {lunch: 'chicken'};
放在控制器中帮助了我。我还发现需要从HTML单选按钮中删除我的ng-checked="true"
,因为在控制器中设置它会自动/编程方式选择正确的单选按钮。 - Keith DC$parent
假定了某种HTML结构(例如,没有介入的ng-include或其他可能创建子作用域的指令)。使用对象属性,您不必担心如果更改HTML会破坏代码。 - Mark Rajcok