AngularJS > Conditional Display

Switch in AngularJS

How to show hide elements based on switch conditions in AngularJS?


In case we have requirement to show / hide or or more element in html page based on certain conditions, we can use ng-switch directive.

ng-switch directive has ng-switch-when and ng-switch-default sub directives that works only within ng-switch scope.

Look at the code snippet below, the model for drop down is "dropSelection" that is set as ng-switch. Based on value selected in the drop down, the ng-switch-when directive is validated and correspondig element is shown to the user. If no value of the drop down is matching with the ng-switch-when directive value then ng-switch-default element is shown to the user.

<div ng-app>
    <select ng-model="dropSelection" ng-init="dropSelection = 'Select'">
        <option value="ASP">ASP</option>
        <option value="JSP">JSP</option>
        <option value="PHP">PHP</option>
        <option value="Select">Select</option>
    </select>

    <div ng-switch="dropSelection">
        <div ng-switch-when="ASP">ASP is a server side scripting language developed by Microsoft</div>
        <div ng-switch-when="JSP">JSP is a server side scripting language developed for Java</div>
        <div ng-switch-when="PHP">PHP is a open source server side scripting language</div>
        <div ng-switch-default>Please select from drop down</div>
    </div>
</div>

Output

Switch in AngularJs

 Views: 2412 | Post Order: 44




Write for us