1

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!

2
  • 2
    ng-disabled? Commented May 2, 2014 at 12:00
  • OMG! AngularJS is so complex and complete. How can anyone ever learn what it offers. I did not know this existed. Commented May 2, 2014 at 12:06

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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';
};

Comments

1

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.

2 Comments

I am going to use your clean-up technique because as you said it becomes so much more readable but then I will use ng-disabled as @RGraham suggested. Thanks!
I see - I thought the question was more to do with simplifying the UI logic. Remember that ng-show and ng-disabled do behave differently; ng-show can hide a control (display:none) and ng-disabled can disable a control (grey it out).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.