在这件事上我已经绞尽脑汁好一阵子了。
我有一个使用ng-model
、ng-required
和ng-change
输入的复选框
取消选中复选框时,我希望ng-model
设置为false,但实际上设置为undefined
此外,当ng-required
表达式切换时,ng-model
还会在未定义的和false之间来回切换,这反过来会导致ng-change
触发。
我实际的ng-change代码执行一些我不想多次运行的代码。
下面这个简单的代码片段显示了我遇到的问题。我在这个例子中加入了一个文本输入,看看它是否做了同样的事情。当用户输入一个字符串,然后删除它时,它似乎做了同样的事情...
这个问题不是关于文本输入的……我最惊讶的是,当ng-required
为true时,ng-required
false值不是有效的复选框值。
var app = angular.module('example', []);
app.controller('controller',['$scope', function($scope){
$scope.inputModel = {
isSelected: undefined,
textInput: undefined
};
$scope.onChangeCounter = 0;
$scope.requiredModel = true;
$scope.resolveCheckboxInput = function() {
if (typeof $scope.inputModel.isSelected === "undefined") {
return "I am undefined"
}
return "I am " + $scope.inputModel.isSelected
};
$scope.resolveTextInput = function() {
if (typeof $scope.inputModel.textInput === "undefined") {
return "I am undefined"
}
return "I am " + $scope.inputModel.textInput
};
$scope.onChangeCallback = function() {
$scope.onChangeCounter++;
};
$scope.isRequired = function() {
return $scope.requiredModel;
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="example">
<ul>
<li> Set Checkbox Input to TRUE</li>
<li> Set Checkbox Input to FALSE</li>
<li> Toggle ng-required</li>
<li> Checkbox Input is cleary affected</li>
</ul>
<div ng-controller="controller">
<label>
<input type="checkbox"
ng-required="isRequired()"
ng-change="onChangeCallback()"
ng-model='inputModel.isSelected' />
Checkbox Input
</label>
<br><br>
<div>
<b>Checkbox Input:</b> {{resolveCheckboxInput()}}
</div>
<br><br>
<label>
<input type="text"
ng-required="isRequired()"
ng-model='inputModel.textInput' />
Text Input
</label>
<br><br>
<div>
<b>Text Input:</b> {{resolveTextInput()}}
</div>
<br><br>
<label>
<input type="checkbox"
ng-model='requiredModel' />
ng-required
</label>
<br><br>
<div>
<b>Checkbox Input ng-change Counter:</b> {{onChangeCounter}}
</div>
</div>
</div>
发布于 2019-03-08 07:15:34
功劳归功于这个问题/答案:Checkbox input undefined when unchecked - AngularJS
您需要添加ng-model-options
。
<input type="checkbox"
ng-required="isRequired()"
ng-change="onChangeCallback()"
ng-model='inputModel.isSelected'
ng-model-options="{ allowInvalid: true }" />
我通常会将此标记为重复的,但链接中的答案不被接受,因此它可能不是很明显的工作。
https://stackoverflow.com/questions/55051343
复制相似问题