ng-show ="true"但仍有class ="ng-hide"

Jos*_*osh 46 forms angularjs ng-show

我是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>
Run Code Online (Sandbox Code Playgroud)

这是我进入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>
Run Code Online (Sandbox Code Playgroud)

Kay*_*ave 88

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>
Run Code Online (Sandbox Code Playgroud)

演示小提琴

要理解为什么让我们看一下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');
    });
  };
}];
Run Code Online (Sandbox Code Playgroud)

关键是要关注它attr.ngShow.当您将该属性设置为{{(doors + windows) < 6}}发生的第一件事时,将评估双花括号中的表达式.在您的情况下,门窗开始,undefined因此表达式评估为false.然后false传入属性.所以a $watch被放置false并且每个$digest循环都false被检查,并且false保持不变,false因此监视功能永远不会运行.

需要注意的重要一点是,属性本身没有被监视,但是最初传入的值被监视.因此,即使您稍后将属性更改为"true",并在html中看到该更改,但手表从未注意到这一点.

的情况下,相反,我们通过在(doors + windows) < 6attr.ngShow随后对每个$digest所述$watch计算该表达式.每当表达式的结果发生变化时,都会调用watch函数并设置相应的类.