Tarun Dugar
Tarun Dugar

Reputation: 8971

AngularJS: ng-show vs display:none

I had a use case whereby I have to keep an HTML element hidden by default using CSS as follows:

HTML:

<div class="item">
</div>

CSS:

.item {
    display: none;
}

But, I need to toggle the element's visibility using ng-show after the page has loaded as follows:

<div class="item" ng-show="show_element">
</div>

But, even if $scope.show_element is set to true, the element doesn't become visible, that is, the css property is overriding AngularJS' ng-show. Is there any way to give ng-show more priority?

Also, you may think I can keep $scope.show_element as false initially to hide it. But in that case, I get a very short glimpse of the element when the page is loading which is not good from the UX point of view.

Upvotes: 12

Views: 27377

Answers (4)

lemmingworks
lemmingworks

Reputation: 179

If you are just trying to hide the item so that you don't get a flash on-load, then instead of using the .item class set to display:none, you could simply set a class of .ng-hide to the element with ng-show on.

The AngularJS directive ng-show works by adding or removing a class of .ng-hide to the DOM element. The .ng-hide class applies the rule display: none !important;

<div class="ng-hide" ng-show="showElement">...</div>

Upvotes: 1

shreedhar bhat
shreedhar bhat

Reputation: 4825

Another simple alternative

style="{{show_element?'display:block !important':'display:none !important'}}"

Upvotes: 5

Griessbrei
Griessbrei

Reputation: 29

I would simply change the class. Ng-shows function is to simply add or remove the ng-hide class, which only propertie is a "display: none !important;". It is not ment to change the css of the classes.

What you could simply do is something like this:

<div class="{{element_class}} item">
</div>

And set the element_class to your class with display:block;

Working example: http://codepen.io/GriessbreiLP/pen/EVXQjK

Hope this might help you.

Edit: Nah, too slow, already mentioned two times.

Upvotes: -2

maurycy
maurycy

Reputation: 8465

One way to make it work in your case would be using ng-class where in case when element should be visible you can apply class with correct display property i.e. display: block and if you suffer from slow bootstrap you can use ng-cloak check documentation here https://docs.angularjs.org/api/ng/directive/ngCloak

Upvotes: 6

Related Questions