jgravois
jgravois

Reputation: 2579

AngularJS: Can I disable a form control based on a variable?

I have three user roles (Coordinator, Resource, and User). I have several controls in a form that should be disabled/read-only for the User but not disabled for the other roles.

In my scope I have a variable of current_user[0].role with possible values of co, re, us respectively.

I am currently using ng-show and duplicating the control but these forms are getting very long and complex and I KNOW THERE HAS TO BE A BETTER WAY.

Here's what I'm using now:

<div class="row">
    <div class="form-group col-lg-6">
        <label for="">Time on Task</label>
        <input type="text" ng-model="TOT" ng-show="current_user[0].role=='co' || current_user[0].role=='re'" />
        <input type="text" ng-model="TOT" disabled="disabled" ng-show="current_user[0].role=='us'" />
    </div>
</div>

Someone PLEASE show me a better way.

Thanks in advance!

Upvotes: 1

Views: 1872

Answers (3)

Gruff Bunny
Gruff Bunny

Reputation: 27976

You could add properties onto your scope for each of the 3 possible roles:

$scope.isCoordinator = current_user[0].role=='co';
$scope.isResource = current_user[0].role=='re';
$scope.isUser = return current_user[0].role=='us';

The view then becomes much more readable:

<input type="text" ng-show="isCoordinator || isResource " />

If the current_user can change within the view you can add a watch on the current_user and update the properties as appropriate.

You could even add those properties to the current_user object.

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78525

Using the ng-disabled attribute:

<input type="text" ng-model="TOT" ng-disabled="current_user[0].role=='us'" />

This will add the disabled attribute when current_user[0].role=='us' is matched. For every HTML attribute, there is normally an ng-* equivalent.

Upvotes: 2

anon
anon

Reputation:

Put a function on your controller to deal with the logic, then call that function using ng-show or ng-disabled. Then you can unit test that function and you keep your templates less cluttered:

$scope.checkUserRole = function(current_user){
    return current_user[0].role=='co' || current_user[0].role=='re';
};

Upvotes: 2

Related Questions