Thursday, 28 September 2017

ng-if in angular JS


ng-if in angular JS :
In angular JS ng-if is used to create or destroy the element from the DOM tree structure of the HTML page.The ng-if directive expects an expression that which makes the result to be in true or false.

The ng-if Look :

<div ng-if="sal > 30000">
Ravi’s salary is 80000

</div>



The div tag contains the ng-if directive with an expression like checking the “sal” model with greater than 30000 or not. The element displays only if, ng-if expression returns true, else it wont display.

ng-if also allows us to have multiple  conditions if wanted based on ||(or) or &&(and) .


<div ng-if="sal < 30000 || sal> 50000 ">

           Ravi’s salary is 70000
</div>
<div ng-if="sal < 100000 && sal > 50000 ">
           Ravi’s salary is 70000
</div>
Sample Example Look :
<script type="text/javascript">
        var myapp = angular.module("MyModule", []);
        myapp.controller("MyCtrl", ["$scope", function ($scope) {          

        }]);
    </script>
HTML Code :
<body ng-app="MyModule" ng-controller="MyCtrl">
    <div>
        <input type="checkbox" ng-model="chk" />
        <div ng-if="chk">
            ng-if removes or creates the element structure from DOM.
        </div>    
    </div>
</body>



In the above code if we see, ng-if directive was added to the inner div and its value as “chk”.Above to that we place the checkbox type and attached ng-model value “chk”. If the checkbox is checked the ng-model value becomes true and the ng-if value too becomes true and creates that concern element, else if the checkbox was unchecked then the ng-model value “chk” model becomes false and ng-if becomes false and deletes the element from the DOM structure too.

ng-if is not equivalant to the ng-show and ng-hide directives, difference between them is like the former the ng-if completely wash out the element where as the next ng-show or ng-hide makes the differ at visibile property from its css.

If any properties or events attached to that element were added dynamically then after re-creation means like after making ng-if expression to true will not reproduce the properties or its associated events that were added dynamically.



4 comments: