1

I have this dropdown with three roles:

  1. Super Admin
  2. Admin
  3. User

And this checkbox that sets some extra privileges

  • Give 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>
w0ns88
  • 344
  • 2
  • 9
  • 28

2 Answers2

2

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;
    }
};
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

First you are missing an ng-model on your md-checkbox. You can bind givePrivileges variable with the md-checkbox. Then you can write a watch statement on the value of role. and update the givePrivileges variable as needed.

HTML

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

JS

$scope.$watch('model.role', function (newVal, oldVal) {
    if (newVal && newVal !== oldVal) {
        if (newVal === ''User) {
            $scope.model.givePrivileges = false;
        }
    }
});
Hassan Mahmud
  • 484
  • 4
  • 13