我有一系列应用程序。该数组的一个子集被插入另一个数组。
$scope.applicant.selectedApps = [];
$scope.applicant.applications = applications;
angular.forEach(applications, function (application) {
if(application.isSelected){
$scope.applicant.selectedApps .push(application);
}
}
我知道有 2 个 ng-repeats 在这些数组上循环:
<div class="row">
<div class="form-group col-sm-10 col-sm-offset-1">
<div class="radio">
<label>
<input type="radio" name="intent" ng-model="applicant.intent" value="Y" required />YES
</label>
</div>
<div class="row" ng-show="applicant.intent == 'Y'">
<div class="col-xs-11 col-xs-offset-1">
<div class="row" ng-repeat="app in applicant.selectedApps">
<div class="col-sm-11 col-sm-offset-1">
<div class="checkbox">
<label>
<input id="Prog{{app.appid}}" name="Progs" type="checkbox" ng-model="app.isSelected" ng-change="appChange(app)" ng-required="applicant.intent == 'Y'" />
{{app.Objective}} - {{app.Name}} - {{app.Description}}
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-10 col-sm-offset-1">
<div class="radio">
<label>
<input type="radio" name="intent" ng-model="applicant.intent" value="N" required />NO
</label>
</div>
<div class="row" ng-show="applicant.intent == 'N'">
<div class="col-xs-11 col-xs-offset-1">
<div class="row" ng-repeat="dApp in applicant.applications">
<div class="col-sm-11 col-sm-offset-1">
<div class="checkbox">
<label>
<input id="dProg{{dApp.appid}}" name="dProgs" type="checkbox" ng-model="dApp.isSelected" ng-change="dProgChange(dApp)" ng-required="applicant.intent == 'N' && appCount <= 0" />
{{dApp.Objective}} - {{dApp.Name}} - {{dApp.Description}}
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
两个变化函数如下:
$scope.dProgChange = function (app) {
if (app.isSelected) {
$scope.appCount++;
} else {
$scope.appCount--;
}
};
$scope.ProgChange = function (app) {
if (app.isSelected) {
$scope.selectedAppCount++;
} else {
$scope.selectedAppCount--;
}
};
我观察到的是,一旦单选按钮切换为“否”,每个使用“isSelected”= false 初始化的应用程序都将设置为未定义。当切换回“YES”时,选择切换回 false。
这会导致每次单选按钮值更改时触发 dProgChange。
我不明白为什么“isSelected”会切换为未定义。
更新 在尝试创建一个简化的示例时,我注意到只要需要复选框就会出现问题。 在下面列出的 plunker 中,一旦取消选中复选框,复选框的模型值就会设置为未定义。在我看来,这与我遇到的问题相同。
最佳答案
这就是 AngularJS(ng-model
和 NgModelController
)应该工作的方式。
NgModelController有两个属性:$viewValue
(用户输入的值)和$modelValue
(绑定(bind)到模型的值)。当用户输入的值验证失败时,NgModelController
将模型设置为未定义。
在 AngularJS 1.3 中,他们添加了 ng-model-options指示。它允许您配置模型更新的方式/时间。您可以使用 allowInvalid
选项来防止您的模型被设置为未定义:
<input type="checkbox"
ng-model="myModel.value"
ng-model-options="{allowInvalid: true}">
关于javascript - 当 ng-repeat 上的复选框具有 required 属性时,Angular ng-model 更改为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29156272/