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

时间:2016-06-24 19:42:18

标签: 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>

对于我的控制器:

(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;
    });
}());

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

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

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

1 个答案:

答案 0 :(得分:17)

背后的原因是,你正在使用%&amp;你在其中定义ng-repeat变量。 ng-model的工作方式是,它在每次迭代的集合中创建一个新的子范围(原型继承)。因此,ng-repeat模板中的ng-model属于新创建的范围。这里ng-repeat ng-model="selectedOccurrence"每次迭代selectedOccurrence创建ng-repeat范围变量。

要解决此类问题,您需要在AngularJS中定义模型时遵循dot rule

<强>标记

<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>

<强>代码

$scope.model = {}; //defined a model object
$scope.model.selectedOccurrence = 'current'; //and defined property in it

Demo Plunkr

OR另一种首选方式是在声明控制器时使用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>

ControllerAs Demo