ng-if
This directive is responsible of manipulating the DOM tree based on an expression that we provide to it. There’s a significant difference between ng-show
(a directive discussed after this one) and ng-if
in that, ng-show
does not remove or create DOM elements but it simply toggles them being displayed or not (sets their display value to be hidden via CSS). If the expression provided to ng-if
evaluates to false, the element will be removed from the DOM tree, and if the expression evaluates to true, a cloned version of the element is reinserted into the DOM – it’s important to note that the original element will be reinserted – so if we were to dynamically change the colour of the text in a paragraph, then remove it using ng-if
and then re-inserting it, the colour styling will not be there anymore – a clean, new copy is inserted at all times.
<!DOCTYPE html>
<html ng-app>
<head>
<title>My first Angular app</title>
</head>
<body>
Check to reveal the Sith Lord <input type="checkbox" ng-model="ischecked">
<p>The secret Sith Lord is <span ng-if="ischecked">Darth Bane</span>
<script src="angular.js"></script>
</body>
</html>
ng-show / ng-hide
As mentioned before neither ng-show
nor ng-hide
manipulates the DOM, they simply change the visibility of an element by adding the CSS class ng-hide
to the element which adds a ‘display: none’ property to the element.
We can rework the previous example to use ng-show
:
<!DOCTYPE html>
<html ng-app>
<head>
<title>My first Angular app</title>
</head>
<body>
Check me to see Luke's father <input type="checkbox" ng-model="ischecked">
<p ng-show="ischecked">Anakin Skywalker</span>
<script src="angular.js"></script>
</body>
</html>
The above only uses the ng-show
directive but we can get a bit more creative and use ng-show/ng-hide
together in the following way also leveraging ng-init
:
<!DOCTYPE html>
<html ng-app>
<head>
<title>My first Angular app</title>
</head>
<body>
<div ng-init="number = 19">
Your guess: <input type="number" ng-model="guess">
<p ng-hide="guess !== number">Correct</p>
<p ng-show="guess !== number">Incorrect</p>
</div>
<script src="angular.js"></script>
</body>
</html>
We are creating a div and using the ng-init
directive, we are creating an expression called ‘number’ to the in the div tag. We are then creating a model using the ng-model
directive called ‘guess’. We can use the value entered in the input box leveraging Angular’s data-binding features and make a comparison between the entered value (guess) and the value created with ng-init
(number) and we are showing/hiding the text based on the result of the comparison. Of course we can write the ng-hide
/ng-show
options the other way around as well:
<p ng-show="guess === number">Correct</p>
<p ng-hide="guess === number">Incorrect</p>
which translates to ‘show me the <p>
tag if the numbered entered in the ‘guess’ input field is the same as the number. Go ahead and give this a try.