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

我是AngularJS的新手,所以可能会有一个简单的解决scheme来解决我的问题。 我一直在做这个表格。 我有两个input – 一个是门的数量,一个是窗口的数量。 然后,我有几个div,如果他们遇到一定数量的总门窗,我想表明。 当我input数字时,ng-showparsing为“true”。 但是这个元素仍然有一个“隐藏”的类,它仍然隐藏起来。

以下是我的代码示例:

<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> 

当我input3个门和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需要一个Angularexpression式,所以你不需要双花括号。

这将为你工作:

 <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}} ,首先发生的是评估双花括号中的expression式。 在你的情况下,门窗开始undefined所以expression式评估为false 。 然后将false传递给属性。 所以$watch被放置在false并且每个$digest周期的false被检查,并且false一直是false所以watch函数永远不会运行。

重要的是要注意的是,该属性本身没有被监视,但是最初传入的值被监视。 所以,即使你后来改变属性为“真”,并看到在HTML中的变化,这从来没有注意到手表。

相反,当我们传入(doors + windows) < 6作为attr.ngShow然后在每个$digest$watch评估该expression式。 并且每当expression式的结果改变时,watch函数被调用并且相应的类被设置。