Part 14 : ng-switch in AngularJs



The ng-switch directive allows the user to insert and remove elements conditionally, from the HTML DOM. It mainly swaps the HTML DOM structure conditionally on the template based on a scope expression.

We will use these three directives of switch case in below example.

ng-switch
ng-switch-when
ng-switch-default

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
       <meta charset="utf-8" />
    <script src="scripts/angular.js"></script>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function () {});
    </script>
</head>
<body ng-controller="myCtrl">
    <div>
        Enter any number (1 to 5): <input type="text" placeholder="Enter number" ng-model="MyNumber"/>
    </div>
    <br /><br /><br /><br />
    <div ng-switch="MyNumber">
        <div ng-switch-when="1" style="border: 1px solid black; width:300px">
            You've entered number 1
        </div>
        <div ng-switch-when="2" style="border: 1px solid red; width:300px">
            You've entered number 2
        </div>
        <div ng-switch-when="3" style="border: 1px solid green; width:300px">
            You've entered number 3
        </div>
        <div ng-switch-when="4" style="border: 1px solid yellow; width:300px">
            You've entered number 4
        </div>
        <div ng-switch-when="5" style="border: 1px solid grey; width:300px">
            You've entered number 5
        </div>
        <div ng-switch-default style="border: 1px solid aqua; width:300px">
            No number has entered yet!!  (default case)
        </div>
    </div>
</body>
</html>

Output:





No comments:

Post a Comment