AngularJs ng-switch template

The “ng-switch” directive is used to behave similar to the switch case in general programming scenario.

In AngularJs ng-switch is used to swap between the HTML DOM elements bases on the data model wrote in the expression.

In the below example we have we have defined a div elements with an ng-switch attribute and on attribute.

The on attribute tell on which data of the model the switch will be applied on. Inside the switch element we have three <div> elements.

The first two elements have the attribute “ng-switch-when” and the last div element have the attribute ng-switch-default. They act same as the switch case.

If the related data model contains the value matched to the given value then the respective div will be shown else the default div will be shown.

Example,
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Demo</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script >
        var myApp = angular.module("AngularApp",['ngRoute']);
        myApp.controller("exampleCtrl", function($scope) {
            $scope.switchVal = {};
            $scope.switchVal.exactVal = "three"

        });
    </script>
</head>

<body ng-app="AngularApp">
<div ng-controller="exampleCtrl">
    <div ng-switch on="switchVal.exactVal">
        <div ng-switch-when="one">You wanted to show first div since you have entered one.</div>
        <div ng-switch-when="two">You wanted to show second div since you have entered two.</div>
        <div ng-switch-when="three">You wanted to show third div since you have entered three.</div>
        <div ng-switch-default>You are in default switch case.</div>
    </div>
</div>
</body>
</html>

The Result looks like,

About Blogger

ANIL SINGH

Hey! I am Anil Singh. I am Active Blogger, Writer and Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book