forms - ng-show ="true"但仍然有类 ="ng-hide"

标签 forms angularjs ng-show

我是 AngularJS 的新手,所以我的问题可能有一个简单的解决方案。我一直在研究这个表格。我有两个输入——一个是门的数量,一个是 window 的数量。然后我有几个 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>

最佳答案

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>

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');
    });
  };
}];

关键是它 Handlebars 表放在attr.ngShow .当您将该属性设置为 {{(doors + windows) < 6}} 时发生的第一件事是计算双花括号中的表达式。在你的情况下,门窗开始undefined所以表达式的计算结果为 false .然后false传递给属性。所以一个 $watch放在 false和每个 $digest周期false已检查,并且 false一直在false所以 watch 功能永远不会运行。

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

相反,当我们传入 (doors + windows) < 6attr.ngShow然后在每个 $digest $watch计算该表达式。每当表达式的结果发生变化时,就会调用 watch 函数并设置适当的类。

关于forms - ng-show ="true"但仍然有类 ="ng-hide",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21129912/

相关文章:

C# 为标签获取好的颜色

ruby-on-rails - 为什么 submit_tag 生成名称为 ="commit"属性的 HTML?

javascript - 是否可以通过更改可写属性描述符来更改 JavaScript 文件名?

javascript - 尝试使用 onclick 事件提交表单,并在 formData 中附加值

javascript - AngularJS 将自定义过滤器的结果传递给另一个自定义过滤器

javascript - AngularJS-错误 : $injector:unpr Unknown Provider userService

javascript - 指令内的随机 ng-show

javascript - Angular2 - 类属性上的双向数据绑定(bind)

javascript - 错误 : this. getToken 不是函数

javascript - ng-animate 无法在 angularjs 1.1.5 中与 ng-show 一起使用