且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

角ng-if和ng-show组合

更新时间:2022-02-18 04:02:23

+1关于Denis的答案,但仅出于完整性考虑,甚至可以通过将逻辑保留在View中而不污染"控制器来进一步简化它:

+1 on Denis's answer, but just for completeness-sake, it can even be simplified further by keeping the logic in the View without "polluting" the controller:

<button ng-click="show = !show">toggle</button>
<div ng-if="once = once || show" ng-show="show">Heavy content</div>

朋克车

可以通过一次性绑定来进一步改进(简化)上述版本,以减少once上不必要的$ watch-仅在Angular 1.3+中有效:>

the version above could be further improved (and simplified) with one-time binding to reduce an unnecessary $watch on once - this will only work in Angular 1.3+:

<div ng-if="::show || undefined" ng-show="show">Heavy content</div>

需要undefined来确保监视的值不稳定" "变成true.一旦稳定下来,它也会失去$ watch,因此不会受到show的任何进一步更改的影响.

The undefined is needed to ensure that the watched value does not "stabilize" before it becomes true. Once it stabilizes, it also loses the $watch, so it would not be impacted by any further change to show.