How to declare ng-show and ng-hide in one div

In my project, I had a requirement to use both ng-show and ng-hide in the same div . I felt this was a bad practice.

html code:

 <div ng-hide="itemDIv2" ng-show="itemDIv2"> <input type="text" placeholder="Item Name" ng-model="itemname"> <div> <input type="submit" class="btn" value="Save" ng-click="subcatiems()> </div> </div> 

another div:

 <div><button class='btn' ng-click="catitems2()">Add items to Category</button></div> 

controller:

 $scope.catitems2 = function(){ return $scope.itemDIv2 = true; } 

how to accept the condition that it is initially hidden, and when the button is pressed, I want to make ng-show="itemDIv2" to true so that I can show the div another file.

+6
source share
3 answers

To add a comment to @vp_arth, you do not need both. But you're on the right track with a boolean flag.

I would suggest making the following changes:

Add this object to the control area:

 $scope.ui = { showDiv: false }; 

And in the template, change the button to:

 button ng-click="ui.showDiv = !ui.showDiv" / 

And instead of ng-show and ng-hide use:

 ng-show="ui.showDiv" 

This way you don't need the catitems2 () function, and the div or what you want to show starts to hide.

Here's the working JSFiddle of the changes:

http://jsfiddle.net/Lvc0u55v/6534/

+3
source

You do not need both ng-show and ng-hide on the same element to fulfill this function. You can switch the scope variable $scope.itemDIv2 at the click of a button.

 <div class="settings-heading " style="background-color: #f2f2f2;" ng-show="itemDIv2" ng-init='itemDIv2=true'> Demo text </div> <div> <button class='btn' ng-click="itemDIv2 = !itemDIv2" > Add items to Category </button> </div> 

Working JSBin: https://jsbin.com/vaduwan/2/edit?html,js,console,output

+4
source

Both ngShow and ngHide simply add / remove the NG_HIDE_CLASS class to the element.

Try reading the sources to understand that: ngShowHide

Use one logical scope variable and set it to the desired value using one of these directives.

+1
source

All Articles