Pravin
Pravin

Reputation: 441

How to use switch case in angularjs and how can I return the value?

I have created a scope like this

var myApp = angular.module("myApp", []);
myApp.controller("MyController", function MyController($scope){ 
$scope.sample = [
{'NUMBER' : '1'},{'NUMBER' : '2'},{'NUMBER' : '3'},{'NUMBER' : '4'}
]
});

I have tried like this.In this I need to retrieve the value which is return form the switch case and to display it in a particular field.

<div  ng-repeat = "grp_val in sample">
<div ng-switch-on="{{grp_val.NUMBER}}">
   <div ng-switch-when="1" ng-init="value='ONE'"></div>
   <div ng-switch-when="2" ng-init="value='TWO'"></div>
   <div ng-switch-when="3" ng-init="value='THREE'"></div>
   <div ng-switch-when="4" ng-init="value='FOUR'"></div>
</div>
 <label>{{VALUE}}</label>
</div>

But its not working.Kindly give some solution.

Upvotes: 0

Views: 4222

Answers (1)

Sarjan Desai
Sarjan Desai

Reputation: 3733

You have used ng-repeat for div and trying to use ng-switch inside ng-repeat which is not proper solution you are trying to implement.

Syntax for ng-switch-on is not proper. It should be ng-switch and on=Expression. Check the Documentation

The way you are trying to init value using ng-init also not work because when code first execute, all div which have ng-switch-when doesn't init value and when selected div becomes visible, it's not init value from div because of life-cycle.

Check working demo with working ng-switch

Upvotes: 2

Related Questions