...">

OnClick radio button show hide div angular js

My code

<form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> </form> <div id="reddiv">Red Selected</div> <div id="greendiv">Green Selected</div> <div id="bluediv">Blue Selected</div> 

my script -

 function Ctrl($scope) { $scope.color = 'blue'; if ($scope.color == 'blue') { //blue div show } else if($scope.color == 'green') { //green div show } else { //red div show } } 

I need to show based on the click of a switch, I tried a piece of code higher than I gave, any idea

+7
angularjs
source share
2 answers

Angular would use the ngShow / ngHide / ngIf to display the corresponding div. Consider this example:

 app.controller('Ctrl', function($scope) { $scope.color = 'blue'; $scope.isShown = function(color) { return color === $scope.color; }; }); 

HTML:

 <div ng-show="isShown('red')">Red Selected</div> <div ng-show="isShown('green')">Green Selected</div> <div ng-show="isShown('blue')">Blue Selected</div> 

Demo: http://plnkr.co/edit/yU6Oj36u9xSJdLwKJLTZ?p=preview

It is also very important that ng-controller="Ctrl" move above your form, because the dives should be in the same area.

+3
source share

You are trying to change the view directly from your controller. This is not an angular way. Pull the model state from the view outside the controller. For example:

 <div ng-show="color == 'red'">Red Selected</div> <div ng-show="color == 'green'">Green Selected</div> <div ng-show="color == 'blue'">Blue Selected</div> 
+14
source share

All Articles