angularjscheckboxdropdownangularjs-ng-disabled

Uncheck a checkbox when it is ng-disabled AngularJS


I have this dropdown with three roles:

  1. Super Admin
  2. Admin
  3. User

And this checkbox that sets some extra privileges

What I want to achieve is this: When the User role is selected in the dropdown, the checkbox is BOTH disabled and unchecked. I have managed to disable it but if it has been checked beforehand, then it remains checked when disabled.

Here is my code:

$scope.model = {
    role: '',
    roles: ['Super Admin', 'Admin', 'User'],
    givePrivileges: false
}

HTML:

<md-input-container>
    <label>Role</label>
    <md-select ng-model="model.role">
        <md-option ng-repeat="role in model.roles" ng-value="role">
            {{role}}
        </md-option>
    </md-select>
</md-input-container>
<md-input-container>
    <md-checkbox ng-disabled="model.role === 'User'">
        Give extra privileges
    </md-checkbox>
</md-input-container>

Solution

  • First, assign ng-model:

    <md-checkbox ng-model="model.givePrivileges" ng-disabled="model.role === 'User'">
        Give extra privileges
    </md-checkbox>
    

    Then handle dropdown change:

    <md-select ng-model="model.role" ng-change="handleRoleChange()">
        <md-option ng-repeat="role in model.roles" ng-value="role">
            {{role}}
        </md-option>
    </md-select>
    

    In controller:

    $scope.handleRoleChange = function () {
        if ($scope.model.role === 'User') {
            $scope.model.givePrivileges = false;
        }
    };