B.Balamanigandan B.Balamanigandan - 4 months ago 75
AngularJS Question

How to write Switch Statement in angularJS Controller

How to write Switch Statement in angularJS Controller ?

My Source Code is

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td><a href="" ng-click="SwitchFuction(x.Name, x.Sno)">{{ x.Country }}</a></td>
</tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {

$scope.names = [
{ Sno: '1', Name: 'Jani', Country: 'Norway' },
{ Sno: '2', Name: 'Hege', Country: 'Sweden' },
{ Sno: '3', Name: 'Kai', Country: 'Denmark' }
];

$scope.SuperFunction = function (id) {
alert(id);
};

$scope.SwitchFuction = function (name, sno) {
switch (sno) {
case '1'
alert("1. Selected Name: " + name );
break;
case '2'
alert("2. Selected Name: " + name );
break;
default:

}
};

});
</script>

</body>
</html>


How to Write the Switch Statement within the function SwitchFuction ???
In the above Source Code contains some semantic error. Kindly assist how to write the Switch Statement?

The Error Screen : FireFox Screen Shot

Answer

there is a syntax error in your SwitchFunction after each case : is missing correct code:

$scope.SwitchFuction = function (id, caseStr) {
        switch (caseStr) {
            case '1':
                alert("Selected Case Number is 1");
                break;
            case '2':
                alert("Selected Case Number is 2");
                break;
            default:

        }
    };