AngularJS ngReadonly Directive



  • The ng-readonly directive in AngularJS used to sets the readonly attribute of a form field (Like input or textarea).
  • It specifies the readonly attribute of an element.
  • The input field will be readonly if the expression inside the ng-readonly attribute returns true.
  • The ng-readonly directive is necessary to move the value between true and false.
  • In HTML, we cannot set the readonly attribute value to false(The presence of read only attribute makes the element value is readonly)
  • This directive executes at priority level 100.

Syntax for ng-readonly directive in AngularJS:

<input ng-readonly=”expression”></input>

Parameter Values:

Value Description
expression If the expression is true then the special attribute “readonly” will be set on the element.

Sample coding for ng-readonly directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorial</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"> </script>
    </head>
    <body ng-app="">
        <h3>ng-readonly directive example in AngularJS Tutorial</h3>
         check me the input field is readonly:
        <input type="checkbox" ng-model="all"><br><br>
        <input type="text" ng-readonly="all">  
    </body>
</html>

Using ng-readonly directive in AngularJS:

<input type="checkbox" ng-model="all"><br><br>
<input type="text" ng-readonly="all">
  • The ng-readonly directive specifies the readonly attribute of an element.

Code Explanation for ng-readonly directive in AngularJS:

Code Explanation for AngularJS ngReadonly Directive

  1. The ng-app specifies the root element (e.g. <body> or <html> or <div> tags) to define AngularJS application.
  2. The “checkbox” is declare the type value of the <input> tag.
  3. The ng-model bind an input field value to AngularJS application variable (“all”).
  4. The “text” is declare the type value of the <input> tag.
  5. The ng-readonly directive sets the readonly attribute of an input field. Here sets the ng-readonly directive to “all”.

Sample Output for ng-readonly directive in AngularJS:

Sample Output for AngularJS ngReadonly Directive

  1. The output displays the default value of the readonly element.
Sample Output for AngularJS ngReadonly Directive

  1. If the user unclick the checkbox then type the text in the input field as “wikitechy”. But the user the click the checkbox that means does not type anything in the input field.
  2. Here the output shows the “wikitechy” text does not changed because it is a readonly element.

Related Searches to angularjs ngReadonly directive