我是 AngularJS 的新手,所以我的问题可能有一个简单的解决方案。我一直在研究这个表格。我有两个输入——一个是门的数量,一个是 window 的数量。然后我有几个 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>
demo fiddle
要了解为什么让我们看看
ngShow
source code :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');
});
};
}];
关键是它 Handlebars 表放在
attr.ngShow
.当您将该属性设置为 {{(doors + windows) < 6}}
时发生的第一件事是计算双花括号中的表达式。在你的情况下,门窗开始undefined
所以表达式的计算结果为 false
.然后false
传递给属性。所以一个 $watch
放在 false
和每个 $digest
周期false
已检查,并且 false
一直在false
所以 watch 功能永远不会运行。需要注意的重要一点是属性本身没有被监视,但最初传入的值被监视。因此,即使您稍后将属性更改为“true”,并在 html 中看到该更改, watch 也从未注意到。
相反,当我们传入
(doors + windows) < 6
如 attr.ngShow
然后在每个 $digest
$watch
计算该表达式。每当表达式的结果发生变化时,就会调用 watch 函数并设置适当的类。
关于forms - ng-show ="true"但仍然有类 ="ng-hide",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21129912/