12

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.

Yogeshree Koyani
  • 1,653
  • 7
  • 19
Tarun Dugar
  • 8,451
  • 6
  • 38
  • 68

4 Answers4

5

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

maurycy
  • 8,393
  • 1
  • 25
  • 42
  • `ng-cloak` sounds like the op's root issue. However be aware angular needs to have loaded on the page for it to take effect. Angular doesn't have to be bootstrapped but it does need to be loaded. Otherwise you will need to target the attribute with css yourself if you have a slow loading page for what ever reason. – ste2425 Oct 09 '15 at 07:35
5

Another simple alternative

style="{{show_element?'display:block !important':'display:none !important'}}"
shreedhar bhat
  • 4,223
  • 1
  • 14
  • 23
0

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>
lemmingworks
  • 149
  • 1
  • 5
-1

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.

Griessbrei
  • 31
  • 5