Subscribe via RSS Feed

Directive in Angular.js – Part 2

May 7, 2014 11 Comments

This article is the continuation of the previous article on Angualr.js Directive. Here we will be getting to accustom ourselves with few of the ng directives in angularjs. In this article we have shown how to use some of the directives in angularjs.

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.

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

  <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <link rel="stylesheet" href="style.css" /> 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script> 
    <script src="app.js"></script> 
  </head> 

  <body ng-controller="MainCtrl"> 
    <p>Welcome to Angular.js</p> 
    check me to select: <br>Male <input type="checkbox" ng-model="select"> 
    female <input type="checkbox" ng-model="selected"> 
    <br/> 
<select> 
<option></option> 
  <option id="gret" ng-selected="select">Hello Mr.</option> 
  <option id="greet" ng-selected="selected">Hello Mrs.</option> 
</select> 
  </body> 

</html> 

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

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <details id="details" ng-open="open">
   <summary>check to Show/Hide <input type="checkbox" ng-model="open"></summary>
   <li>John</li>
   <li>Dave</li>
   <li>Rick</li>
   <li>Jason</li>
</details>
  </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.

ngshow and nghide both of the directives generally co-exist together. So we are going to demonstrate a set of codes , where by checking the textbox we can hide or show some specific texts.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   Click me to see the changes in the below: <input type="checkbox" ng-model="checked"><br/>
<div>
  Show:
  <div class="check-element" ng-hide="checked">
   check the checkbox to make me disapper.
  </div>
</div>
<div>
  Hide:
  <div class="check-element animate-show" ng-show="checked">
   your checkbox is checked.
  </div>
</div>
  </body>

</html>

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

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
<input type="button" value="set" ng-click="myStyle={color:'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<br/><br/>
<span ng-style="myStyle">Sample Text</span>
  </body>
</html>

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 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 follows HTML5 input types and poly fills the HTML5 validation behavior for older browsers.

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 rows. In this sample we are going to put some data in 4 different rows. The odd ones will be colored red. For this with the html we are going to put some rule into css too.

Let us see our html codes.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <h3>Using ng-class-odd</h3>
  <!--we are initializing the data in rows-->
    <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
    <!-- using ng-repeat we are able to search for odd rows throughout the document-->
  <li ng-repeat="name in names">
   <span ng-class-odd="'odd'">
     {{name}}
   </span>
  </li>
</ol>
  </body>

</html>

As for the stylesheet rule we can use this:

.odd {
  color: red;
}

ngClassEven – As we have seen in ngClassOdd , ngClassEven works in the same way but on the even rows. As before we will have a css file and an html file. But taking in mind the previous one , this example has a slight change it changes the texts , which are in even rows.

Let us see through the html code.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <h3>Using ng-class-even</h3>
  <!--we are initializing the data in rows-->
    <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
    <!-- using ng-repeat we are able to search for even rows throughout the document-->
  <li ng-repeat="name in names">
   <span ng-class-even="'even'">
     {{name}}
   </span>
  </li>
</ol>
  </body>

</html>

Now, the css file.

.even {
  color: red;
}

ngInclude – Fetches, compiles and includes an external HTML fragment. By default, the template URL is restricted to the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on it. To load templates from other domains or protocols you may either white-list them or wrap them as trusted values. Refer to Angular’s Strict Contextual Escaping.

In addition, the browser’s Same Origin Policy and Cross-Origin Resource Sharing (CORS) policy may further restrict whether the template is successfully loaded. For example, ngInclude won’t work for cross-domain requests on all browsers and for file:// access on some browsers.

In the following set of codes we have included 2 html pages ‘samplepage1′ , ‘samplepage2′ and their contents using ng-include.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
    <script>function Ctrl($scope) {
  $scope.templates =
    [ { name: 'samplepage1.html', url: 'samplepage1.html'},
      { name: 'samplepage2.html', url: 'samplepage2.html'} ];
  $scope.template = $scope.templates[0];
}</script>
  </head>

  <body ng-controller="MainCtrl">
   <div ng-controller="Ctrl">
  <select ng-model="template" ng-options="t.name for t in templates">
   <option value="">(blank)</option>
  </select>
  url of the template: <tt>{{template.url}}</tt>
  <hr/>
  <div class="slide-animate-container">
    <div class="slide-animate" ng-include="template.url"></div>
  </div>
</div>
  </body>

</html>

ngTransclude – Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
 <script>
  function Ctrl($scope) {
    $scope.title = 'Title';
    $scope.text = 'Text Area';
  }

  angular.module('transclude', [])
   .directive('pane', function(){
      return {
        restrict: 'E',
        transclude: true,
        scope: { title:'@' },
        template: '<div style="border: 1px solid black;">' +
                    '<div style="background-color: gray">{{title}}</div>' +
                    '<div ng-transclude></div>' +
                  '</div>'
      };
  });
</script>
<div ng-controller="Ctrl">
  <input ng-model="title"><br>
  <textarea ng-model="text"></textarea> <br/>
  <pane text="{{text}}">{{title}}</pane><br/>
  <pane title="{{title}}">{{text}}</pane>
</div>
  </body>

</html>

ngInit – The ngInit directive allow us to evaluate an expression in the current scope.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <script>
function Ctrl($scope) {
  $scope.list = [['a', 'b','e'], ['c', 'd']];
}
</script>
<div ng-controller="Ctrl">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
     <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  </div>
</div>
</div>
  </body>

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
  </body>

</html>

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.

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
    <script>function Ctrl($scope) {
  $scope.items = ['settings', 'home', 'other'];
  $scope.selection = $scope.items[0];
}</script>
  </head>

  <body ng-controller="MainCtrl">
   <div ng-controller="Ctrl">
  <select ng-model="selection" ng-options="item for item in items">
  </select>
  <tt>selection={{selection}}</tt>
  <hr/>
  <div class="animate-switch-container"
    ng-switch on="selection">
      <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
      <div class="animate-switch" ng-switch-when="home">Home Span</div>
      <div class="animate-switch" ng-switch-default>default</div>
  </div>
</div>
  </body>

</html>

This article is the continuation of the previous one. Here we will be getting to accustomed ourselves with few of the ng directives in angularjs.

Related Links:
1>Directive in Angular.js – Part 1
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.