Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 one div. I felt that's 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 take a condition that initially it is on hide and when the button is clicked i want to make ng-show="itemDIv2" to true so that I can show the div one more tome.

like image 635
Sukumar MS Avatar asked Jul 06 '16 04:07

Sukumar MS


3 Answers

You don't need both ng-show and ng-hide on same div to acheive this functionality. You can toggle the scope variable $scope.itemDIv2 on button click.

<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

like image 56
Aditya Singh Avatar answered Oct 16 '22 19:10

Aditya Singh


To expand on on @vp_arth's comment, you don't need both. But you're on the right track with the boolean flag.

I would suggest making these changes:

Add this object to the controller scope:

$scope.ui = { showDiv: false };

And in the template, change the button to:

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

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

ng-show="ui.showDiv"

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

Here's a working JSFiddle of the changes:

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

like image 43
RoboBear Avatar answered Oct 16 '22 21:10

RoboBear


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

Try read the sources to understand that: ngShowHide

Use one boolean scope variable and set it to neccesary value with one of that directives.

like image 1
vp_arth Avatar answered Oct 16 '22 21:10

vp_arth