Today we would learn frequently used Angular JS directives.
Solution:- We would achieve it by using built in directives of Angular JS.
1. ng-Switch:-We can control the conditional display of data.
It is similar to Switch-Case in JavaScript.
JavaScript syntax:-
Switch(expression) {
Case n: Code Break; Case n1: Code Break; Default: Default code
Angular JS syntax:-
Lets have corresponding code for above flow using directives:-
ng-switch on = expression
ng-switch-when = n Code ng-switch-when = n Code ng-switch-default Code
We also need to use ng-switch-when & ng-switch-default directives same as Case and Default in Javascript
Example:-
<div ng-app> EnterColor: <input type = "text" ng-model="Color"/> <div ng-switch on = "Color"> <span ng-switch-when="red" style="color:{{Color}}"> I am very RED </span> <span ng-switch-when="green" style="color:{{Color}}"> I am very GREEN </span> <span ng-switch-default style="color:{{Color}}"> I am default </span> </div>
</div>
2. ng-If:- Used to remove/recreate the DOM element based on the expression.
Syntax:- ng-if=”Conditional-Expression“
Note:-when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored.
Example:-
<div ng-app> Check for Red Color: <input type = "checkbox" ng-model="Color"/> <div ng-if = "Color" style="width:50px;height:50px;background-color:red;"> </div> <div ng-if = "!Color" style="width:50px;height:50px;background-color:green;"> </div>
</div>
Note: – Unlike ng-if, it is not deleting and recreating the element from DOM but simply changing the display CSS of the element.
Syntax:-ng-Hide=”expression“
How it works: –
- All it uses is Class =”ng-hide” and this class have CSS property of “display:none !important”.
- !important so that this property have the maximum weight and cannot be overridden.
- When expression is true then .ng-hide CSS is added causing element to be hidden and vice-verse.
Note: – For ng-Show we have ng-hide class added on “False” condition and removed when condition is “true” (it is reverse case as of ng-Hide)
Example:-
Example:-
<div ng-app> Show Me: <input type = "checkbox" ng-model="Color"/> <div ng-show = "Color" style="width:50px;height:50px;background-color:red;"> </div> Hide Me: <input type = "checkbox" ng-model="hideColor"/> <div ng-hide = "hideColor" style="width:50px;height:50px;background-color:green;"> </div>
</div>
- We can check the ng-hide class, using the inspect element.
At launch of code
Check the “Show Me” checkbox