问题描述
有人可以向我解释为什么在这个简单的例子中我无法获得当前选中的单选按钮。我正在尝试使用ng-repeat指令动态生成单选按钮,并使用ng-model选择当前的单选按钮。
喜欢这个:
Could someone explain to me why I can't get the current selected radio-button in this simple example. I'm trying to generate dynamically the radio-buttons with an ng-repeat directive and get the current radio-button selected using ng-model.Like this:
模板:
<div ng-repeat="kind in movieKinds">
<input type="radio" name="movies" ng-value="kind" ng-model="kindSelected"> {{kind.name}}<br>
</div>
Selected Movie :{{kindSelected}}
控制器:
mymodule.controller('MainCtrl', [ '$scope',function ($scope) {
$scope.movieKinds = [
{'name' : 'Action', 'movies' : ['Action#1', 'Action#2', 'Action#3']},
{'name' : 'Comedy', 'movies' : ['Comedy#1', 'Comedy#2', 'Comedy#3']},
{'name' : 'Drama', 'movies' : ['Drama#1', 'Drama#2']},
{'name' : 'Horror', 'movies' : ['Horror#1']}
];
}]);
推荐答案
因为 ng-repeat
在每次迭代时创建一个新的子作用域(原型继承),当它在任何位置重复 ng-repeat
指令时重复模板。
Because ng-repeat
does create a new child scope(prototypically inherited) on each iteration when it repeats a template on wherever ng-repeat
directive has been placed.
在子范围内,它包含 primitive
的所有属性创建子范围时所用的属性初始值& object
值与其引用一起使用,因此在父范围值
中的更新将在子范围值和更新中更新。反之亦然。
In the child scope it carries all properties in which primitive
property initial value taken while creating child scope & object values are taken with their references so update in parent scope value will update in child scope value & vice versa.
在你的情况下你有 ng-model =kindSelected
变量 ng-repeat
,以便在 ng-repeat
范围内创建范围变量并且不可用外部 ng-repeat
指令。
Here in your case you had ng-model="kindSelected"
variable inside ng-repeat
so that scope variable got create inside the ng-repeat
scope and doesn't available outside ng-repeat
directive.
要解决此类问题,您可以使用 object
在定义 ng-model
时,您可以在定义<$ c $时遵循 Dot规则
C> NG-模型。这意味着您可以在控制器和放大器中定义一个名为 $ scope.model
的对象。然后添加 kindSelected
属性,以便在选中复选框时更新该值。
To fix such a problem you could use object
while defining ng-model
so that you could follow Dot rule
while defining ng-model
. That means you could define a object called as $scope.model
inside controller & then add kindSelected
property so that the value will get updated on selection of checkbox.
标记
<div ng-repeat="kind in movieKinds">
<input type="radio" name="movies" ng-value="kind" ng-model="kindSelected"> {{kind.name}}<br>
</div>
Selected Movie :{{model.kindSelected}}
代码
$scope.model = {};
解决此问题的另一种方法是使用 controllerAs
语法将使用控制器的别名,因此在HTML上不会发生与范围层次结构相关的问题。无论您想要哪个控制器变量,都可以使用控制器的别名。
The other way to fix this problem is to use controllerAs
syntax which will use alias of controller so the scope hierarchy related problem doesn't happen on HTML. Whichever controller variable you want you could use that alias of the controller.
这篇关于为什么输入不能正确使用ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!