AngularJS: ng-show vs display:none

时光怂恿深爱的人放手 提交于 2019-12-13 12:58:52

问题


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.


回答1:


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




回答2:


Another simple alternative

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



回答3:


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>



回答4:


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.



来源:https://stackoverflow.com/questions/33032081/angularjs-ng-show-vs-displaynone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!