Subscribe via RSS Feed

Directive in Angular.js – Part 1

May 6, 2014 14 Comments

Introduction:

The web, when it first came out was really just designed to display static pages. As we all know it has become very dynamic and we have dealt with that pretty well. jQuery came out many years ago and it provided a way to do it.

Angular takes it up a whole notch and allows us to extend HTML very easily by simply adding attributes, elements or comments. Collection of Directive in Angular.js helps us in achieving this functionality.

WHAT ARE DIRECTIVES?

Directives in AngularJS are used to make custom HTML elements and simplify DOM manipulation. They can modify the behavior of new and existing DOM elements, by adding custom functionality, like a datepicker or an auto-complete widget. AngularJS comes with its own set of built-in directives, as well as the ability to add new ones.

WHY ARE DIRECTIVES USED IN ANGULARJS?

Standard HTML has elements like <span>, <input>, and <button> that have fixed behavior. To make the <input> element behave like a datepicker, it takes custom CSS and JS calls from Javascript code. AngularJS makes this easy by allowing to do all this in what we call a directive. So instead of writing

<input id="datepickerElem"> 

<!--and then calling--> 

$('#datepickerElem').datepicker() 

<!--but in angularjs we ca achieve all this with only one line of code.-- >	

<input datepicker> 

<!--or--> 

<datepicker> 

HOW TO USE DIRECTIVES IN ANGULARJS?

To use directives in angularjs we just need to add the directive name in whatever DOM element we want right in our HTML. For example, a datepicker Directive, depending on how it is defined, could be used as

<input datepicker> 
<!--or--> 
<datepicker>

IN-BUILT DIRECTIVES:

AngularJS comes with a whole set of directives, including ngHide / ngShow, ngClick, ngRepeat and many more. It’s also great in that the AngularJS inbuilt directives use the same API that we will use to write our own directives.

<!DOCTYPE html> 
<!-- using ng in tag means to tell html that the rest of the code is under 
angularjs--> 
<!-- ng is a angularjs built on directive--> 
<html ng-app> 

  <head> 
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
  </head> 

  <body> 
    <h5>welcome angularjs</h5> 
    <div class="container"> 

      <!--ng-model stores up a property called name in memory--> 
      name:<input type ="text" ng-model="name" /> {{name}} 
    </div> 
  </body> 

</html> 

now as we have a basic idea of in-built directives in angularjs. Let as venture through the many other built-in directives that angularjs has.

In-Built Directives:

ngApp- Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page – e.g.

<html ng-app> 

ngHref - Using Angular markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{hash}} markup with its value. Until Angular replaces the markup the link will be broken and will most likely return a 404 error.

<a ng-href="http://www.google.com/{{hash}}"/>

ngSrc – Using Angular markup like {{hash}} in a src attribute doesn’t work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

<img ng-src="http://www.google.com/images{{hash}}"/>
<div ng-init="scope = { isDisabled: false }">
 <button disabled="{{scope.isDisabled}}">Disabled</button>
</div> 

ngSelected – The HTML specification does not require browsers to preserve the values of boolean attributes such as selected. If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngSelected directive solves this problem for the selected attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.

ngOpen – The HTML specification does not require browsers to preserve the values of boolean attributes such as open.

ngRepeat – The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key. Let us look through a set of codes where we have created an array with different value. And repeat directive calls them one after another, as per the array index.

<!DOCTYPE html> 
<!-- using ng in tag means to tell html that the rest of the code is under 
angularjs--> 
<!-- ng is a angularjs built on directive--> 
<html ng-app> 

  <head> 
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
  </head> 

  <body> 
    <h1>welcome angularjs</h1> 
    <div class="container"> 

      <!--ng-model stores up a property called name in memory--> 
      name:<input type ="text" ng-model="name"> 
      </div> 
      <div class="container"
      ng-init="names=['foo','bar']">

      <h3>looping with ng-repeat directive</h3>
      <ul>
        <li ng-repeat='name in names'>
          {{name}}
        </li>

      </ul>

      </div>

  </body> 

</html>

ngShow – The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element.

ngHide – The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute.

ngStyle – The ngStyle directive allows you to set CSS style on an HTML element conditionally.

ngForm – Nestable alias of form directive. HTML does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.

form Directive are that instantiates FormController.

textarea

HTML textarea element control with angular data-binding. The data-binding and validation properties of this element are exactly the same as those of the input element.

input

HTML input element control with angular data-binding. Input control

ngModel – The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using ngModelController, which is created and exposed by this directive.

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="[email protected]" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello AngularJs!</h1>
    <script>
 function Ctrl($scope) {
   $scope.val = '1';
  }
</script>

Update input to see transitions when valid/invalid.
Integer is a valid value.
<form name="testForm" ng-controller="Ctrl">
  <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>
  </body>

</html>

ngChange – Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change . The expression is not evaluated when the value change is coming from the model.

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="[email protected]" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello AngularJs!</h1>
   <script>
  function Controller($scope) {
    $scope.counter = 0;
    $scope.change = function() {
      $scope.counter++;
    };
  }
</script>
<div ng-controller="Controller">
  <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  <label for="ng-change-example2">Confirmed</label><br />
  <tt>debug = {{confirmed}}</tt><br/>
  <tt>counter = {{counter}}</tt><br/>
</div>
  </body>

</html>

ngList – Text input that converts between a delimited string and an array of strings. The delimiter can be a fixed string (by default a comma) or a regular expression.

<script>
  function Ctrl($scope) {
    $scope.names = [];
  }
</script>
<form name="myForm" ng-controller="Ctrl">
  List: <input name="namesInput" ng-model="names" ng-list required>
  <span class="error" ng-show="myForm.namesInput.$error.required">
    Required!</span>
  <br>
  <tt>names = {{names}}</tt><br/><div>
  <!--<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>--></div>
 </form>

ngValue – Binds the given expression to the value of input[select] or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.

 <script>
   function Ctrl($scope) {
     $scope.names = ['pizza', 'unicorns', 'robots'];
     $scope.my = { favorite: 'unicorns' };
   }
</script>
 <form ng-controller="Ctrl">
   <h2>Which is your favorite?</h2>
     <label ng-repeat="name in names" for="{{name}}">
       {{name}}
       <input type="radio"
              ng-model="my.favorite"
              ng-value="name"
              id="{{name}}"
              name="favorite">
     </label>
   <div>You chose {{my.favorite}}</div>
 </form>

ngBind – The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

 <script>
  function Ctrl($scope) {
    $scope.name = '';
  }
</script>
<div ng-controller="Ctrl">
  Enter name: <input type="text" ng-model="name" required=""><br>
  Hello <span ng-bind="name"></span>!
</div>

ngClass – The ngClass directive allows you to dynamically set CSS classes on an HTML element by data binding an expression that represents all classes to be added.

ngClassOdd – The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.

ngClassEven – The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.

ngController – The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.

<!DOCTYPE html>
<html ng-app="">

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello AngularJs!</h1>
    <script>
  function SettingsController1() {
    this.name = "";
    this.contacts = [
      {type: 'phone', value: ''},
      {type: 'email', value: ''},
      {type: 'adress', value:''}];
    };

  SettingsController1.prototype.greet = function() {
    alert(this.name);
  };

  SettingsController1.prototype.addContact = function() {
    this.contacts.push({type: 'email', value: '[email protected]'});
  };

  SettingsController1.prototype.removeContact = function(contactToRemove) {
   var index = this.contacts.indexOf(contactToRemove);
    this.contacts.splice(index, 1);
  };

  SettingsController1.prototype.clearContact = function(contact) {
    contact.type = 'phone';
    contact.value = '';
  };
    </script>
    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  Name:       <input type="text" ng-model="settings.name" />

  [       <a href="" ng-click="settings.greet()">greet</a>
 ]      <br />
      <br />

  Contact:
        <ul>
        <li ng-repeat="contact in settings.contacts">
          <select ng-model="contact.type">
            <option>phone</option>
            <option>email</option>
            <option>adress</option>
          </select>
          <input type="text" ng-model="contact.value" />

      [           <a href="" ng-click="settings.clearContact(contact)">clear</a>

      |           <a href="" ng-click="settings.removeContact(contact)">X</a>
 ]
    </li>
        <li>[           <a href="" ng-click="settings.addContact()">add</a>
 ]</li>
      </ul>
    </div>
  </body>

</html>

ngInclude – Fetches, compiles and includes an external HTML fragment.

ngInit – The ngInit directive allows you to evaluate an expression in the current scope.

ngNonBindable – The ngNonBindable directive tells Angular not to compile or bind the contents of the current DOM element. This is useful if the element contains what appears to be Angular directives and bindings but which should be ignored by Angular. This could be the case if you have a site that displays snippets of code, for instance.

ngSwitch – The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location as specified in the template.

We will come with Part 2 of this post with different examples.

Related Links:
1>Directive in Angular.js – Part 2
2>Working with Modules in Angular.js
3>Angular Router and UI-Router
4>Angularjs and Services
5>Angular.js Promise
6>Angular.js Two Way Data Binding
7>How To Use Filter In Angular.js
8>Angular Templates
9>Using Controllers in Angular.Js
10>Angularjs with Server Side Interaction
11>Working Through Angular.js With Transclude
12>Angular.js Event Handling

If you find this article helpful, you can connect us in Google+ and Twitter.