AngularJS ngselected



  • The ng-selected directive in AngularJS used for sets the selected attribute of a form field (<option>) or it specifies the selected attribute of an element.
  • It is supported by <option> element in a <select> list.
  • If the expression inside the ng-selected attribute returns the true value means the option will be selected.
  • The ng-selected directive is necessary to move the value between true and false.
  • In HTML, we cannot set the selected attribute value to false (The presence of selected attribute makes the element value is selected)/li>
  • This directive executes at priority level 100.

Syntax for ng-selected directive in AngularJS:

<option ng-selected=”expression” ></option>

Parameter Values:

Value Description
expression Denotes an angular expression that will set the element’s selected attribute if it returns true.

Sample coding for ng-selected directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"></script>
    </head>
    <body ng-app="">
        <h3>ng-selected directive in AngularJS Tutorial </h3>
        Click here to Select CSS Tutorials: <input type="checkbox" ng-model="value">
        <p>Select Tutorial</p>
        <select>
            <option>HTML</option>
            <option ng-selected="value">CSS</option>
            <option>PHP</option>
        </select>
    </body>
</html>

ng-selected Directive in Angular JS:

<select>
    <option>HTML</option>
    <option ng-selected="value">CSS</option>
    <option>PHP</option>
</select>
  • The ng-selected directive is used for selected attribute of an element.

Code Explanation for ng-selected directive in AngularJS:

Code Explanation for AngularJS ngselected

  1. The ng-app specifies the root element (“<body>”) 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 (“value”).
  4. <select> tag is used to create a drop down list for HTML, CSS and PHP.
  5. <option> tag is used to described an option in a select list such as HTML, CSS and PHP.
  6. The ng-selected directive is used for selected attribute of an element. Here the “CSS” is declare the ng-selected value of <option> tag.

Sample Output for ng-selected directive in AngularJS:

Sample Output1 for AngularJS ngselected

  1. The checkbox is displayed in the output with the default value of an HTML in an option list.

Sample Output2 for AngularJS ngselected

  1. If the user clicks the checkbox button, then the selected value of “CSS” is displayed in the output.


Related Searches to angularjs ngselected directive