我试图将单选按钮列表中的选定值绑定(bind)到 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>
对于我的 Controller :
(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;
});
}());
在第一部分中,我尝试 ng-repeat 所有 occurrenceOptions
并将它们全部绑定(bind)到同一个模型。但是,每次我选择某些内容时,selectedOccurrence
值都不会改变。
参见插件:https://plnkr.co/edit/k1pMgkLdrMUG1blktQx1?p=preview
没有 ng-repeat
并且只需输入所有单选按钮,我就能让它工作。为什么 ng-repeat
版本不起作用?
最佳答案
它不起作用的原因是,您正在使用 ng-repeat
并且您正在其中定义 ng-model
变量。 ng-repeat
的工作方式是,它在集合的每次迭代中创建一个新的子范围(原型(prototype)继承)。因此,位于 ng-repeat
模板中的 ng-model
属于新创建的范围。这里 ng-model="selectedOccurrence"
在 ng-repeat
的每次迭代中创建 selectedOccurrence
范围变量。
要克服这样的问题,您需要在 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>
代码
$scope.model = {}; //defined a model object
$scope.model.selectedOccurrence = 'current'; //and defined property in it
或者另一种首选方法是在声明 Controller 时使用 controllerAs
模式(在 Controller 内使用 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>
关于javascript - AngularJs:将 ng-model 绑定(bind)到单选按钮列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020982/