Tuesday, 12 April 2016

Understanding ng-if, ng-switch and ng-repeat directives

AngularJS provides you ng-if, ng-switch directives to display HTML elements based on conditions or cases. ng-repeat directive is used to generate HTML from a collection of items.



ng-if


This directive can add / remove HTML elements from the DOM based on an expression. If the expression is true, it add HTML elements to DOM, otherwise HTML elements are removed from the DOM.


  1. ng-controller="MyCtrl">


  2. ng-if="data.isVisible">ng-if Visible

  3. </div>

  4.  


  5. var app = angular.module("app", []);

  6. app.controller("MyCtrl", function ($scope) {

  7. $scope.data = {};

  8. $scope.data.isVisible = true;

  9. });



ng-switch


This directive can add / remove HTML elements from the DOM conditionally based on scope expression.


  1. ng-controller="MyCtrl">


  2. ng-switch on="data.case">


  3. ng-switch-when="1">Shown when case is 1


  4. ng-switch-when="2">Shown when case is 2


  5. ng-switch-default>Shown when case is anything else than 1 and 2

  6. </div>

  7. </div>

  8.  


  9. var app = angular.module("app", []);

  10. app.controller("MyCtrl", function ($scope) {

  11. $scope.data = {};

  12. $scope.data.case = true;

  13. });



ng-repeat


This directive is used to iterate over a collection of items and generate HTML from it.


  1. ng-controller="MyCtrl">


  2. ng-repeat="name in names">

  3. {{ name }}



  4.  


  5. var app = angular.module("app", []);

  6. app.controller("MyCtrl", function ($scope) {

  7. $scope.names = ['Shailendra', 'Deepak', 'Kamal'];

  8. });



What do you think?


I hope you will enjoy the ng-if, ng-switch and ng-repeat directives in AngularJS while developing your app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment