为什么输入不适用于 ng-repeat

Why the inputs are not working right with ng-repeat

有人可以向我解释为什么在这个简单示例中我无法获取当前选定的单选按钮。我正在尝试使用 ng-repeat 指令动态生成单选按钮,并使用 ng-model 选择当前的单选按钮。 像这样:

模板:

<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 指令的任何地方重复一个模板时。

So what happens when ng-repeat creates a new prototypically inherited child scope?

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-repeat 中有 ng-model="kindSelected" 变量,因此范围变量在 ng-repeat 范围内创建,并且在 ng-repeat 指令之外不可用。

要解决此类问题,您可以在定义 ng-model 时使用 object,这样您就可以在定义 ng-model 时遵循 Dot rule。这意味着您可以在控制器中定义一个名为 $scope.model 的对象,然后添加 kindSelected 属性 以便在选择复选框时更新该值。

标记

<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 上。无论您想要哪个控制器变量,您都可以使用该控制器的别名。