Angular ng-show directive doesn't work for but

2019-07-19 06:47发布

I have angular.js web application and btn-group in there like:

<div class="btn-group>
  <button class="btn btn-default hidden-xs">....</button>
  <button class="btn btn-default hidden-xs">....</button>
  <button class="btn btn-default hidden-xs">....</button>
</div>

I want to hide one of button and added:

<button ng-show="show_button">....</button>

And in controller

$scope.show_button = false;

But i see button. Why? ng-show works for whole btn-group but not for one button.

5条回答
Rolldiameter
2楼-- · 2019-07-19 07:03

Try replacing ng-show/ng-hide with ng-if. Should do the trick :)

查看更多
\"骚年 ilove
3楼-- · 2019-07-19 07:07

I ran into this issue too. Finally I found that I set the style "visibility: hidden" in my own CSS file to the div. So no matter how I change the expression in ng-show, div is always hidden. That means the visibility style in your own style is always applied, angularjs will never change this css property value. To use ng-show/ng-hide the first thing you need to make sure is that you do NOT add any show/hide style to DOM element, just hand over the control to angular.

查看更多
▲ chillily
4楼-- · 2019-07-19 07:08

I just ran into this problem using Angular v1.2.2.

It appears that Bootstrap's style rules for .hidden-xs:

.hidden-xs { display: block !important; }
@media (max-width: 767px) {
    .hidden-xs { display: none !important; }
}

override the style rules from Angular's (v1.2.2) injected inline stylesheet (prepended instead of appended to the head) for .ng-hide (presumably, .ng-show as well).

[ng\:cloak], [ng-cloak], [data-ng-cloak],
[x-ng-cloak], .ng-cloak, .x-ng-cloak,
.ng-hide {
    display: none !important;
}

For lack of better solution at the moment, add the angular stylesheet or specific rules that you need to your document, stylesheet or in some other fashion. (Then check for style rule changes if you change versions of Angular). If anyone has a more appropriate solution, feel free to contribute.

查看更多
Fickle 薄情
5楼-- · 2019-07-19 07:16

Here is the plunkr example for you. It works for me in btn-group.

查看更多
对你真心纯属浪费
6楼-- · 2019-07-19 07:22

bootstraps' .hidden-xs class adds display:block for visible elemets which breaks angular's ng-show and ng-hide classes.

Instead, use a custom .my-hidden-xs class:

// my-style.css
@media (max-width: 767px) {
    .my-hidden-xs {
        display: none !important;
    }
}

// index.html
<button class="btn btn-default my-hidden-xs" ng-show="show_button"></button>
查看更多
登录 后发表回答