Let us create some custom directives:
Now we read how to create custom directives. We start with some simple examples and move towards some complex custom directives.
Example 1:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <style>
- .sparkline
- {
- background-color: brown;
- font-size: large;
- height: 100px;
- width: 200px;
- color: aqua
- }
- </style>
-
- </head>
-
- <body>
- <h2>AngularJS Custom Directive Example</h2>
- <div ng-app="mainApp">
- <divng-demo>
- </div>
- </div>
-
- </body>
- <script>
- var mainApp = angular.module("mainApp", []);
- mainApp.directive('ngDemo', function()
- {
- return
- {
- restrict: 'A',
- template: '<div class="sparkline">This is simple Custom Directive of Element Type</div>'
- }
- });
- </script>
-
-
- </html>
Output:
In the above example we created a custom directive using the following code.
- mainApp.directive('ngDemo', function()
- {
- return
- {
- restrict: 'A',
- template: '<div class="style_">This is simple Custom Directive of Element Type</div>'
- }
- });
In the above code we defined the name of the directive (ngDemo). Type of the directive is an attribute that is defined by restrict: ‘A’. Here the restrict option is used to define the type of element for which this directive will invoke. In template option we define the text (template) that replaces the content of the element that invokes this directive. Template is an option where we are specifying the html that will be appended or append.
<divng-demo></div>
Using the above code we invoked the directive. Notice that when we invoke it (ng-demo) and the name of directive (ngDemo), both are not the same. This is because AngularJS will handle translating the camel cased name when we define it to the snake case when we invoke it.
Method to build a directive:
In AngularJS we can create the custom directive in two ways. First method is returning a directive description object that we performed in the last example. The second method is using a “link” function. Building a directive with the link function is usually enough for relatively simple directives. We will read about this method later in this article.
The templateUrl:
In the previous example we define inline template. Instead of this inline template we can define html text in a file and implement this file using the templateUrl, which will use ajax to pull the template.
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <style>
- .style_
- {
- background-color: brown;
- font-size: large;
- height: 300px;
- width: 300px;
- color: aqua
- }
- </style>
-
- </head>
-
- <body>
- <h2>AngularJS Custom Directive Example</h2>
- <div ng-app="mainApp">
- <divng-demo>
- </div>
- </div>
-
- </body>
- <script>
- var mainApp = angular.module("mainApp", []);
- mainApp.directive('ngDemo', function()
- {
- var directive = {};
- directive.restrict = 'A';
- directive.templateUrl = "index.html";
- return directive;
- });
- </script>
-
-
- </html>
Index.html:
This is TemplateUrl Example.
- <br/>
- <div class="style_">This is simple Custom Directive of Element Type<br/>
- <bstyle="color:#BFEF10">delhi is capital of India</b>
- <img src="delhi.png" />
- </div>
Output:
In the above example we create an index .html page and load this page using the templateUrl property,
directive.templateUrl = "index.html";
Isolating the $scope from the Directive:
- <%@RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="ajaxToolkit"%>
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
-
- </head>
-
- <body>
- <h2>AngularJS Custom Directive Example</h2>
- <div ng-app="mainApp" ng-controller="MyController">
-
-
- <userinfouser="pankaj">
- </userinfo><br/>
- <userinfouser="rahul">
- </userinfo><br/>
- <userinfouser="sandeep">
- </userinfo><br/>
- </div>
- </body>
-
-
-
- <script>
- var myapp = angular.module("mainApp", []);
- myapp.directive('userinfo', function()
- {
- var directive = {};
- directive.restrict = 'E';
- directive.template = "<div> Isolate The $scope</div>";
- return directive;
- });
- </script>
-
-
- </html>
Output:
An isolate scope is a separate scope object tied to the directive. In the previous example we declare the directory,
<userinfouser="pankaj"></userinfo>”. If we want to use same directory multiple times like
<userinfouser="pankaj"></userinfo><userinfouser="sandeep"></userinfo>” then userinfoelements would be replaced by the same HTML template because $scope variables typically have the same values everywhere inside the same controller. Referencing $scope variables directly makes it hard to reuse the directive more than once within the same controller. So to resolve this issue we need to bind the HTML template to an isolate scope.
Example:
- <%@RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="ajaxToolkit"%>
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
-
- </head>
-
- <body>
- <h2>AngularJS Custom Directive Example</h2>
- <div ng-app="mainApp" ng-controller="MyController">
-
-
- <userinfouser="pankaj">
- </userinfo><br/>
- <userinfouser="rahul">
- </userinfo><br/>
- <userinfouser="sandeep">
- </userinfo><br/>
- </div>
- </body>
-
-
-
- <script>
- var myapp = angular.module("mainApp", []);
- myapp.directive('userinfo', function()
- {
- var directive = {};
-
- directive.restrict = 'E';
-
- directive.template = "User : {{user.firstName}} {{user.lastName}} {{user.age}}";
-
- directive.scope =
- {
- user: "=user"
- }
-
- return directive;
- });
- myapp.controller("MyController", function($scope, $http)
- {
- $scope.pankaj = {};
- $scope.pankaj.firstName = "Pankaj";
- $scope.pankaj.lastName = "Choudhary";
- $scope.pankaj.age = 21;
-
- $scope.rahul = {};
- $scope.rahul.firstName = "Rahul";
- $scope.rahul.lastName = "Prajapat";
- $scope.rahul.age = 20;
-
- $scope.sandeep = {};
- $scope.sandeep.firstName = "Sandeep";
- $scope.sandeep.lastName = "Sandeep";
- $scope.sandeep.age = 22;
- });
- </script>
-
-
- </html>
Output:
The compile() and link() functions:
If we want to do something extra in our custom directive then everything is not possible within the HTML template, for this we can use the compile() and link() function. Both methods are used to define how the directive modifies the HTML that matches the directive.
The compile() function used a one time configuration needed of the element containing the directive. The compile() function is called only one time for each occurrence of the directive in the HTML page. The compile() function contains two parameters: element and attributes. The element parameter is a jqLite wrapped DOM element, and the attributes parameter is a JavaScript object containing properties for all the attributes of the DOM element.
The compile() function returns a link function, this link() function is called every time the element is to be bound to data in the $scope object. The link() function takes three parameters: $scope, element, and attributes. The $scope parameter is a normal scope object or an isolated scope if we specified one in the directive definition object. The element and attributes element are same as compile parameters.
Example:
- <%@RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="ajaxToolkit"%>
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
-
- </head>
-
- <body>
- <h2>AngularJS Custom Directive Example</h2>
- <div ng-app="mainApp" ng-controller="MyController">
-
-
- <userinfouser="pankaj">
- </userinfo><br/>
- <userinfouser="rahul">
- </userinfo><br/>
- <userinfouser="sandeep">
- </userinfo><br/>
- </div>
- </body>
-
-
-
- <script>
- var myapp = angular.module("mainApp", []);
- myapp.directive('userinfo', function()
- {
- var directive = {};
-
- directive.restrict = 'E';
-
- directive.template = "User : {{user.firstName}} {{user.lastName}} {{user.age}}";
-
- directive.scope =
- {
- user: "=user"
- };
- directive.compile = function(element, attributes)
- {
- element.css("border", "2px solid blue");
-
- var linkpara = function($scope, element, attributes)
- {
- element.html("User First Name: <b>" + $scope.user.firstName + "</b> , User Last Name: <b>" + $scope.user.lastName + "</b>" + ", User Age: <b>" + $scope.user.age + "</b>");
- element.css("background-color", "yellow");
- }
- return linkpara;
- };
-
- return directive;
- });
- myapp.controller("MyController", function($scope, $http)
- {
- $scope.pankaj = {};
- $scope.pankaj.firstName = "Pankaj";
- $scope.pankaj.lastName = "Choudhary";
- $scope.pankaj.age = 21;
-
- $scope.rahul = {};
- $scope.rahul.firstName = "Rahul";
- $scope.rahul.lastName = "Prajapat";
- $scope.rahul.age = 20;
-
- $scope.sandeep = {};
- $scope.sandeep.firstName = "Sandeep";
- $scope.sandeep.lastName = "Sandeep";
- $scope.sandeep.age = 22;
- });
- </script>
-
-
- </html>
Output:
Custom directives allow us to create the directive as per our requirement and using compile and link function we can add some external styles in custom directive.