Getting Started With Angular – Inbuilt Directive

In the blog post we will see some of the important angular directives and their usage.

Angular directive are HTML tags or attributes which we add to HTML to make it dynamic. We have already seen few important directives likes ng-app and ng-controller.

Below we will see some of the important angular directives

ng-repeat

This acts as a for loop in HTML, to iterate over arrays, collections. Each item inside ng-repeat gets its own scope, with the current item set in it.

Lets see examples of its usage

  
var mainMod = angular.module('MainApp', []);
  
mainMod.controller('MainCtrl', ['$scope','$rootScope',
      
function ($scope,$rootScope) {
           
var demo_array = [];
           
demo_array.push({id:1,name:'Test1′});
           
demo_array.push({id:2,name:'Test2′});
           
demo_array.push({id:3,name:'Test3′});
           
$scope.demo\_array = demo\_array;

var demo_dictionary = {};
           
demo_dictionary['key1′] = {id:1,name:'Test1'};
           
demo_dictionary['key2′] = {id:2,name:'Test2'};
           
demo_dictionary['key3′] = {id:3,name:'Test3′};
           
$scope.demo\_dictionary = demo\_dictionary;

}
  
]);
  

HTML

  
<body ng-app='MainApp'>
      
<div ng-controller='MainCtrl'>
        
<div>
          
<div>Demo Array</div>

<ul>
            
<li id='row.id' ng-repeat='row in demo_array'>
              
{{row.name}} - {{$index}}
            
</li>
          
</ul>

<div>Demo Dictionary</div>

<ul>
            
<li ng-repeat='(key,row) in demo_dictionary'>
              
{{key}} - {{row.name}} - {{row.id}}
            
</li>
          
</ul>

</div>
      
</div>
  
</body>
  

More details can be seen here

ng-if

Based on the expression in ng-if, a DOM element is add or removed.

  
<div ng-if='to_show'>Hi</div>
  

If the expression ‘to_show’ evaluates to true, the ‘div’ will be created else it won’t.

More details here

ng-show

Based on the expression in ng-show, the DOM element will be visible or hidden.

  
<div ng-show='to_show'>Hi</div>
  

If the expression ‘to_show’ evaluates to true; the ‘div’ will be visible else it will be hidden.

More details here

ng-class

ng-class is used to add or remove a ‘class’ of an element dynamically.

More details here

ng-style

ng-style similar to ng-class is used to set the style property of an element.

More details here

ng-src

ng-src is used to dynamically replace an image expression with src attribute for image.

Usage is quite simple

ng-src is important because if we directly write src='{{image}}', there will be a 404 not found error since on page load browser will evaluate src on page load. To avoid this we use ng-src so that on page load we don’t get any image 404 error.

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype