我试图将单选按钮列表中的选定值绑定到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
版本不起作用?
答案 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
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>