AngularJs:将ng-model绑定到单选按钮列表

Rhs*_*Rhs 10 javascript angularjs angularjs-scope angularjs-controller

我试图将单选按钮列表中的选定值绑定到 ng-model

我有:

<!DOCTYPE html>

<html ng-app="testApp">
    <head>
        <script src="./bower_components/angular/angular.min.js"></script>
        <script src="test.js"></script>
    </head>
    <body ng-controller="testController">
        <form>
            <div ng-repeat="option in occurrenceOptions">
                <input type="radio" name="occurrence" ng-value="option" ng-model="selectedOccurrence" /><label>{{ option }}</label>
            </div>
        </form>
        <div>The selected value is : {{ selectedOccurrence }}</div>

        <!-- This works -->
        <input type="radio" ng-model="selected2" ng-value="'1'"> 1
        <input type="radio" ng-model="selected2" ng-value="'2'"> 2
        <input type="radio" ng-model="selected2" ng-value="'3'"> 3

        <div>This selected value is : {{ selected2 }} </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

对于我的控制器:

(function () {

    var app = angular.module('testApp', []);

    app.controller('testController', function($scope) {
        $scope.occurrenceOptions = [];

        $scope.occurrenceOptions.push('previous');
        $scope.occurrenceOptions.push('current');
        $scope.occurrenceOptions.push('next');

        $scope.selected2;
    });
}());
Run Code Online (Sandbox Code Playgroud)

在第一部分中,我尝试重复所有occurrenceOptions并将它们全部绑定到同一模型.但是,每次选择某些内容时,该selectedOccurrence值都不会更改.

请参阅plunkr:https://plnkr.co/edit/k1pMgkLdrMUG1blktQx1 p = preview

没有ng-repeat,只需输入所有的单选按钮,我就可以使用它.为什么ng-repeat版本不起作用?

Pan*_*kar 22

它背后的原因是,你正在使用ng-repeat&你在其中定义ng-model变量.方法ng-repeat是,它在每次迭代的集合中创建一个新的子范围(原型继承).所以ng-model它驻留在ng-repeat模板中,属于新创建的范围.这里在每次迭代时ng-model="selectedOccurrence"创建selectedOccurrence范围变量ng-repeat.

要克服这个问题,您需要dot rule在AngularJS中定义模型时遵循

标记

<body ng-controller="testController">
  <form>
    <div ng-repeat="option in occurrenceOptions track by $index">
      <input type="radio" name="occurrences" ng-value="option" ng-model="model.selectedOccurrence" />
      <label>{{ option }}</label>
    </div>
  </form>
  <div>The selected value is : {{ model.selectedOccurrence }}</div>
</body>
Run Code Online (Sandbox Code Playgroud)

$scope.model = {}; //defined a model object
$scope.model.selectedOccurrence = 'current'; //and defined property in it
Run Code Online (Sandbox Code Playgroud)

演示Plunkr


或另一种首选方法是controllerAs在声明控制器时使用模式(使用this而不是$scope内部控制器).

HTML

<body ng-controller="testController as vm">
    <form>
        <div ng-repeat="option in vm.occurrenceOptions">
            <input type="radio" name="occurrence" ng-value="option" ng-model="vm.selectedOccurrence" /><label>{{ option }}</label>
        </div>
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

ControllerAs Demo