AngularJS: ng-show / ng-hide not working with `{{

2019-01-01 12:39发布

I am trying to show / hide some HTML using the ng-show and ng-hide functions provided by AngularJS.

According to the documentation, the respective usage for these functions are as follows:

ngHide – {expression} - If the expression truthy then the element is shown or hidden respectively. ngShow – {expression} - If the expression is truthy then the element is shown or hidden respectively.

This works for the following usecase:

<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>

However, should we use a parameter from an object as the expression then the ng-hide and ng-show are given the correct true/false value but the values are not treated as a boolean so always return false:

Source

<p ng-hide="{{foo.bar}}">I could be shown, or I could be hidden</p>
<p ng-show="{{foo.bar}}">I could be shown, or I could be hidden</p>

Result

<p ng-hide="true">I should be hidden but I'm actually shown</p>
<p ng-show="true">I should be shown but I'm actually hidden</p>

This is either a bug or I am not doing this correctly.

I cannot find any relative information on referencing object parameters as expressions so I was hoping anyone with a better understanding of AngularJS might be able to help me out?

7条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 13:32

If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch:

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

The paragraph will be displayed when foo.bar is true, hidden when false.

查看更多
登录 后发表回答