我是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>发布于 2014-01-15 13:50:14
ngShow接受一个角度表达式,所以你不需要双花括号。
这将对您起作用:
<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');
});
};
}];关键是它在attr.ngShow上放置了一块手表。当您将该属性设置为{{(doors + windows) < 6}}时,发生的第一件事是计算双花括号中的表达式。在本例中,门和窗从undefined开始,因此表达式的计算结果为false。然后将false传递给该属性。因此,将一个$watch放在false上,并检查每个$digest周期的false,并且false保持为false,因此手表函数永远不会运行。
需要注意的重要一点是,不会监视属性本身,但会监视最初传入的值。因此,即使您稍后将该属性更改为"true",并在html中看到该更改,手表也不会注意到这一点。
相反,当我们将(doors + windows) < 6作为attr.ngShow传入,然后在每个$digest上,$watch都会计算该表达式。只要表达式的结果发生变化,就会调用监视函数并设置适当的类。
https://stackoverflow.com/questions/21129912
复制相似问题