AngularJS技术问题:选中复选框后需清空ng-model="data.closingDay"的值
Solution to Clear
data.closingDay When Checkbox is Selected Got it, let's fix this issue for you. The problem happens because checking the "all" checkbox doesn't automatically reset the data.closingDay model that holds your selected days. We can resolve this with a simple ng-change handler.
Option 1: Using a Controller Function (Best for Readability)
First, update your HTML to add an ng-change event to the checkbox:
<md-input-container> <label>Days</label> <input type="checkbox" ng-model="all" ng-change="onAllCheckboxToggle()"> <md-select ng-model="data.closingDay" multiple ng-disabled="all"> <md-optgroup label="days"> <md-option ng-value="day" ng-repeat="day in days">{{day}}</md-option> </md-optgroup> </md-select> </md-input-container>
Then add this function to your AngularJS controller:
$scope.onAllCheckboxToggle = function() { // When the checkbox is checked, clear the selected days model if ($scope.all) { $scope.data.closingDay = null; } };
Option 2: Inline Expression (Shorter for Simple Logic)
If you prefer a more concise approach without a separate function, you can put the logic directly in the ng-change attribute:
<md-input-container> <label>Days</label> <input type="checkbox" ng-model="all" ng-change="all && (data.closingDay = null)"> <md-select ng-model="data.closingDay" multiple ng-disabled="all"> <md-optgroup label="days"> <md-option ng-value="day" ng-repeat="day in days">{{day}}</md-option> </md-optgroup> </md-select> </md-input-container>
How It Works
- The
ng-changeevent triggers every time the checkbox's state changes. - When
allis set totrue(checkbox checked), we explicitly setdata.closingDaytonull, which clears any previously selected days from the model. - The
ng-disabled="all"on the md-select already prevents further selections once the checkbox is checked, so this completes the desired behavior.
内容的提问来源于stack exchange,提问作者Divakar Yadav
相关产品推荐
相关产品推荐

