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

发布于 2021-02-01 10:14:49

我是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>
关注者
0
被浏览
82
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    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>
    

    演示小提琴

    要理解为什么让我们看一下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}}发生的第一件事时,将计算双花括号中的表达式。在您的情况下,门和窗开始,undefined因此表达式的计算结果为false。然后false传递给属性。因此$watch放置a
    false并检查每个$digest周期false,并false一直保持false下去,因此watch功能永远不会运行。

    需要注意的重要一点是,不会监视属性本身,但是会监视最初传递的值。因此,即使您稍后将属性更改为“ true”,并看到html中的更改,手表也从未注意到。

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看