forms – ng-show =“true”但仍然有class =“ng-hide”

前端之家收集整理的这篇文章主要介绍了forms – ng-show =“true”但仍然有class =“ng-hide”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是新来的AngularJS,所以可能有一个简单的决议,我的问题。我一直在这个表格上工作。我有两个输入 – 一个是门的数量,一个是窗口的数量。然后我有几个div,如果他们满足一定数量的门和窗户,我想显示。当我输入数字到输入,ng-show解析为“true”。但是元素仍然有“ng-hide”类,它仍然隐藏它。

这里是我的代码示例:

  1. <body ng-app>
  2. Doors: <input type="number" ng-model="doors"><br>
  3. Windows: <input type="number" ng-model="windows"><br>
  4.  
  5. <div ng-show="{{(doors + windows) < 6}}">
  6. Shows if you have 0-5 doors and windows combined.
  7. </div>
  8. <div ng-show="{{(doors + windows) > 5 && (doors + windows) < 11}}">
  9. Shows if you have 6-10 doors and windows combined.
  10. </div>
  11. <div ng-show="{{(doors + windows) > 10 }}">
  12. Shows if you have more than 10 doors and windows combined.
  13. </div>
  14. </body>

这是输入3门和4窗口时的输出

  1. <div ng-show="false" class="ng-hide">
  2. Shows if you have 0-5 doors and windows combined.
  3. </div>
  4. <div ng-show="true" class="ng-hide">
  5. Shows if you have 6-10 doors and windows combined.
  6. </div>
  7. <div ng-show="false" class="ng-hide">
  8. Shows if you have more than 10 doors and windows combined.
  9. </div>
ngShow采用一个角度表达式,所以你不想要双大括号。

这将为您工作:

  1. <div ng-show="(doors + windows) < 6">
  2. Shows if you have 0-5 doors and windows combined.
  3. </div>
  4. <div ng-show="(doors + windows) > 5 && (doors + windows) < 11">
  5. Shows if you have 6-10 doors and windows combined.
  6. </div>
  7. <div ng-show="(doors + windows) > 10">
  8. Shows if you have more than 10 doors and windows combined.
  9. </div>

demo fiddle

要了解为什么让我们来看看ngShow source code

  1. var ngShowDirective = ['$animate',function($animate) {
  2. return function(scope,element,attr) {
  3. scope.$watch(attr.ngShow,function ngShowWatchAction(value){
  4. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element,'ng-hide');
  5. });
  6. };
  7. }];

关键是,它把一个手表attr.ngShow。当您将该属性设置为{{(doors windows)< 6}}发生的第一件事是评价双花括号中的表达式。在你的情况下,门和窗口开始未定义,所以表达式的结果为false。然后false被传递给属性。因此,$ watch被置于false,并且每个$ digest周期为false被检查,并且false保持为false,因此watch函数从不运行。 重要的是要注意的是,属性本身没有被监视,但是最初传递的值被监视。因此,即使您稍后将属性更改为“true”,并看到html中的更改,这是从来没有注意到手表。 相反,当我们进入(门窗) 6 as attr.ngShow然后在每个$ digest $ watch评估那个表达式。每当表达式的结果改变时,watch函数调用并且适当的类集合。

猜你在找的Angularjs相关文章