ng-show =“ true”,但仍具有class =“ ng-hide”
我是AngularJS的新手,所以对于我的问题可能有一个简单的解决方案。我一直在处理这种形式。我有两个输入-
一个用于门的数量,一个用于窗户的数量。然后,我要显示几个div,如果它们满足一定数量的门窗总数。当我在输入中输入数字时,ng-show解析为“
true”。但是该元素上仍然具有“ ng-hide”类,因此仍将其隐藏。
这是我的代码示例:
<body ng-app>
Doors: <input type="number" ng-model="doors"><br>
Windows: <input type="number" ng-model="windows"><br>
<div ng-show="{{(doors + windows) < 6}}">
Shows if you have 0-5 doors and windows combined.
</div>
<div ng-show="{{(doors + windows) > 5 && (doors + windows) < 11}}">
Shows if you have 6-10 doors and windows combined.
</div>
<div ng-show="{{(doors + windows) > 10 }}">
Shows if you have more than 10 doors and windows combined.
</div>
</body>
这是我输入3门和4窗口时的输出:
<div ng-show="false" class="ng-hide">
Shows if you have 0-5 doors and windows combined.
</div>
<div ng-show="true" class="ng-hide">
Shows if you have 6-10 doors and windows combined.
</div>
<div ng-show="false" class="ng-hide">
Shows if you have more than 10 doors and windows combined.
</div>
-
ngShow
采用Angular表达式,因此您不需要双花括号。这将为您工作:
<div ng-show="(doors + windows) < 6"> Shows if you have 0-5 doors and windows combined. </div> <div ng-show="(doors + windows) > 5 && (doors + windows) < 11"> Shows if you have 6-10 doors and windows combined. </div> <div ng-show="(doors + windows) > 10"> Shows if you have more than 10 doors and windows combined. </div>
要理解为什么让我们看一下
ngShow
源代码:var ngShowDirective = ['$animate', function($animate) { return function(scope, element, attr) { scope.$watch(attr.ngShow, function ngShowWatchAction(value){ $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); }); }; }];
关键在于它可以监视
attr.ngShow
。当您将该属性设置为{{(doors + windows) < 6}}
发生的第一件事时,将计算双花括号中的表达式。在您的情况下,门和窗开始,undefined
因此表达式的计算结果为false
。然后false
传递给属性。因此$watch
放置a
false
并检查每个$digest
周期false
,并false
一直保持false
下去,因此watch功能永远不会运行。需要注意的重要一点是,不会监视属性本身,但是会监视最初传递的值。因此,即使您稍后将属性更改为“ true”,并看到html中的更改,手表也从未注意到。
的情况下,相反,我们通过在
(doors + windows) < 6
如attr.ngShow
随后对每个$digest
所述$watch
计算该表达式。每当表达式的结果更改时,都会调用watch函数并设置适当的类。
-
何时支持 ng-if 与 ng-show/ng-hide?
2022-03-22 关注 0 浏览39 1答案
-
ng-if和ng-show / ng-hide有什么区别
2021-02-01 关注 0 浏览92 1答案
-
什么时候支持ng-if和ng-show / ng-hide?
2021-02-01 关注 0 浏览108 1答案
-
AngularJS:ng-show / ng-hide 不适用于`{{ }}`插值
2022-07-28 关注 0 浏览8 1答案
-
AngularJS:ng-show / ng-hide不适用于`{{}}`插值
2021-02-01 关注 0 浏览95 1答案
-
为什么从ng-show =“!emptyArray”和ng-hide =“ emptyArray”得到不同的结果?
2021-02-01 关注 0 浏览117 1答案
-
如何使用角度ui路由器进行ng-hide和ng-show视图?
2021-02-01 关注 0 浏览86 1答案
-
在ng-hide / ng-show中是否可能使用复杂的表达式?
2021-02-01 关注 0 浏览81 1答案
-
angular中ng一if和ng-show/hide 有什么区别?
2020-01-14 关注 0 浏览456 1答案
-
替代ng-show / hide或如何仅加载DOM的相关部分
2021-02-01 关注 0 浏览95 1答案