AngularJS, JavaScript

AngularJS Readonly Dropdown

HTML select’s don’t implement the readonly attribute, so the only way to prevent them from being edited is to use the disabled attribute. Doing so however prevents them from being posted on submission. The standard solution for this is create a hidden input field, which you have to keep in sync with the disabled select element. Finally, if your read-only status is dynamically changing based on the editable values in other fields, you’ll have to disable/re-enable the proper fields on the client. AngularJS can be used to get some of this logic contained.

Here’s an example:

HTML:

<div ng-app="app">
	<div ng-controller="dropdownController">
		<select name="cat" ng-model="cat" ng-options="item.value as item.label for item in cats" ng-disabled="catDisabled">  
    </select>
		<input name="cat" type="hidden" ng-disabled="!catDisabled" ng-model="cat">
		<input type="text" ng-model="cat"/>
    <br/>
    <label><input type="checkbox" ng-model="catDisabled"> Disable?</label>
	</div>
</div>

JavaScript:

angular.module('app', []).controller('dropdownController', function($scope){
  $scope.form = [];
  
  $scope.cats = [
    {value: 1, label: 'Mufasa'},
    {value: 2, label: 'Simba'},
    {value: 3, label: 'Scar'},
    {value: 4, label: 'Fluffy'}
  ];
});

JsFiddle:
https://jsfiddle.net/thomaslangston/wgaf9v3q/

Before you go

 
I’d like to get your feedback! Please take a moment to post a comment below to let me know your thoughts on this post. Anything you think should be introduced to a beginner or junior developer ASAP? Or is there a facet to the business of software I’ve overlooked? I would be very happy to hear about either.

Also, I putting together a very focused mailing list on the topics that I regularly cover on this blog. If this post was useful to you, please sign up here to get future emails from me on this and related subjects. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *