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.
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.
- bas practice is to write lo-o-ong lines of code. – Ilya Novojilov Commented Jul 6, 2016 at 4:20
- 2 Why not use ng-if? – user6549300 Commented Jul 6, 2016 at 4:21
- Why you are want this? ngShow/ngHide just reversed version of each other. – vp_arth Commented Jul 6, 2016 at 4:23
- Initialize the $scope.itemDIv2 to false, and remove ng-hide would help. – Nguyen Tuan Anh Commented Jul 6, 2016 at 4:24
3 Answers
Reset to default 5You 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./vaduwan/2/edit?html,js,console,output
To expand on on @vp_arth's ment, 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/Lvc0u55v/6534/
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.