ng-show=“true” but still has class=“ng-hide”

做~自己de王妃 提交于 2019-11-28 16:58:25

ngShow takes an Angular expression so you don't want the double curly braces.

This will work for you:

<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

To understand why let's look at the 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');
    });
  };
}];

The key is that it puts a watch on attr.ngShow. When you set that attribute to {{(doors + windows) < 6}} the first thing that happens is the expression in the double curly braces is evaluated. In your case, doors and windows start out undefined so the expression evaluates to false. Then false is passed in to the attribute. So a $watch is placed on false and every $digest cycle false is checked, and false keeps being false so the watch function never runs.

The important thing to note is that the attribute itself isn't being watched, but the value that was initially passed in is watched. So even though you later change the attribute to "true", and see that change in the html, that's never noticed by the watch.

When, instead, we pass in (doors + windows) < 6 as attr.ngShow then on each $digest the $watch evaluates that expression. And whenever the result of the expression changes the watch function is called and the appropriate class set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!