简体   繁体   English

使用Angular的ng-if

[英]Using Angular's ng-if

Looking at Mastering Web Application Development in Angular , I tried to use the ng-if Directive to not show a <div> if an expression was false . 在Angular掌握Web应用程序开发方面 ,我尝试使用ng-if指令在表达式为false不显示<div>

HTML HTML

<div ng-controller="MyCtrl">
    <div ng-if="showSecret">Secret</div>
</div>

JavaScript JavaScript的

var myModule = angular.module('myApp', []);

function MyCtrl($scope) {  
    $scope.showSecret = (function() { 
        return false;
    })();
}

But, looking at this JsFiddle( http://jsfiddle.net/64GCp/2/ ), I see that Secret gets rendered. 但是,看着这个JsFiddle( http://jsfiddle.net/64GCp/2/ ),我发现Secret被渲染了。 Why? 为什么?

It looks like you are using v1.0.1 and documentation here doesn't show an ngIf document. 看来您使用的是v1.0.1, 此处的文档未显示ngIf文档。

The first instance of it I see is here in version 1.2.0 它的第一个实例我看到的是这里的版本1.2.0

Changing the library version works: http://jsfiddle.net/64GCp/4/ 更改库版本有效: http : //jsfiddle.net/64GCp/4/

The options to hide and show are ng-show or ng-hide and later in version Angularjs 1.2.0+ ngIf 隐藏和显示的选项是ng-showng-hide以及更高版本的Angularjs 1.2.0+ ngIf

http://jsfiddle.net/64GCp/3/ http://jsfiddle.net/64GCp/3/

All directives are executed over the DOM and therefore both ngShow or ngIf will be executed equally. 所有指令都在DOM上执行,因此ngShowngIf将被同等执行。

I have personally used ngShow in a page a large number of times(I decided to used "large number" to highlight the ambiguity) and tested it in all browsers including IE8 with no problems at all. 我曾在页面中多次使用ngShow (我决定使用“大数”来突出显示歧义),并在包括IE8在内的所有浏览器中对其进行了测试,完全没有问题。

What the book is probably referring to is that the size of the page will not change because all ngShow/ngHide does is to hide the element: 这本书可能指的是页面的大小不会改变,因为ngShow / ngHide所做的只是隐藏元素:

ng-show output ng-show输出

  <div ng-show="showSecret" style="display: none;">Secret</div> 

While ngIf only leaves a comment: 而ngIf仅发表评论:

ng-if output ng-if输出

  <!-- ngIf: checked -->

Important: the first stable version to add ng-if was angular 1.2.0 make sure you have this version or higher before planning to use it. 重要提示:添加ng-if的第一个稳定版本是angular 1.2.0,在计划使用它之前,请确保您具有此版本或更高版本。

Please understand 2 things, Angular is rapidly changing framework and so are the browsers it is always a good practice to search for benchmarks/versions to confirm or discard features. 请理解两件事,Angular是一个快速变化的框架,因此浏览器始终是搜索基准/版本以确认或放弃功能的一个好习惯。 It is also possible that the internal functionality of directives may change overtime. 指令的内部功能也可能随着时间的推移而变化。 For instance Angular Team announced that they dropped IE8 support in version 2.0. 例如,Angular Team宣布他们在2.0版中放弃了IE8支持。

The version of angular you are using does not support ng-if. 您使用的angular版本不支持ng-if。 Use a newer version. 使用较新的版本。 See my fiddlehttp://jsfiddle.net/SdYH5/ 看到我的小提琴http://jsfiddle.net/SdYH5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM