2

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.

HTML

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

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. Why?

3
  • Use ngShow or ngHide instead Commented Jan 5, 2014 at 2:08
  • The book says: The ng-show/ng-hide directives are easy to use but might have unpleasant performance consequences if applied to large number of DOM nodes Commented Jan 5, 2014 at 2:09
  • I was trying to remove my -1 (before I saw you deleted your answer) as you said you had used ng-show/ng-hide numerous times. But, if you could please elaborate on why ng-if is wrong, I'd appreciate it. Thank you. Commented Jan 5, 2014 at 2:18

3 Answers 3

3

It looks like you are using v1.0.1 and documentation here doesn't show an ngIf document.

The first instance of it I see is here in version 1.2.0

Changing the library version works: http://jsfiddle.net/64GCp/4/

Sign up to request clarification or add additional context in comments.

Comments

0

The version of angular you are using does not support ng-if. Use a newer version. See my fiddlehttp://jsfiddle.net/SdYH5/

Comments

0

The options to hide and show are ng-show or ng-hide and later in version Angularjs 1.2.0+ ngIf

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

All directives are executed over the DOM and therefore both ngShow or ngIf will be executed equally.

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.

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:

ng-show output

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

While ngIf only leaves a comment:

ng-if output

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.