If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
Please note the old syntax with colon.
There is also a new better way of applying classes conditionally, like:
ng-class="{selected: $index==selectedIndex}"
Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
However these ways are not functionally equal. Here is an example:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
The foo.bar
reference should not contain the braces:
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.
See also Understanding Angular Templates.
Best Answer
Depends on your use case but to summarise the difference:
ng-if
will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, whenng-if
evaluates to false, that element will be removed from DOM and your click handler will not work any more, even afterng-if
later evaluates to true and displays the element. You will need to reattach the handler.ng-show/ng-hide
does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.ng-if
creates a child scope whileng-show/ng-hide
does notElements that are not in the DOM have less performance impact and your web app might appear to be faster when using
ng-if
compared tong-show/ng-hide
. In my experience, the difference is negligible. Animations are possible when using bothng-show/ng-hide
andng-if
, with examples for both in the Angular documentation.Ultimately, the question you need to answer is whether you can remove element from DOM or not?