Skip to main content

How to Convert jQuery Or JavaScript Plugin to Angular Directive

What is a jQuery plugin?
 
When a jQuery prototype object needs to be extended, we create a jQuery plugin which consists of methods that a jQuery object can inherit. A jQuery plugin can be created or customized according to the requirements although there are still several such plugins available online for use. Hence, the jQuery plugin can be thought of as a collection of elements which are called methods/functions. When an object of jQuery is called, all the methods of the prototype, as well as the inherited methods of the plugin, are called together.
 
What is AngularJS Directive?
 
There are several elements defined in AngularJS though there may be times when the need to extend the corresponding HTML comes forth. Custom Directives enable this through a ‘directive’ function which is called in place of the element for which it is defined. This happens only after the linking (link() function) of the element and its directive function after the compilation (compile() function) process. Custom Directives in AngularJS can be created for the following elements,
  1. Element- when a matching element is found, the directive starts working (restrict E)
  2. Attribute- when a matching attribute is found, the directive starts working (restrict A)
  3. CSS- when a matching CSS style is found, the directive begins working (restrict C)
  4. Comment- when a matching comment is found, the directive begins its work (restrict M)
There are several advantages of a custom directive. Directives provide aid in the creation of repeatable code that has the capability to work independently. Whatever the requirements are, all the functions and attributes corresponding to it are encapsulated together. This way there could be multiple directives each with a different scope and function, ready to be called when needed.
 
Typical jQuery plugin initialization
 
Standalone, a jQuery plugin is very easy to use. When you think about its initialization, just go for it in the initializing event of the document: document.ready
  1. <div  id="ng-slider"></div>  
  2. <p>The slider's value is: <span  id="slider-value">0</span></p>    
  3. $(document).ready(function() {  
  4.     // Initialize the slider  
  5.     $('#slider').slider({  
  6.         change: function(event, ui) {  
  7.             $('#slider-value').html(ui.value);  
  8.         }  
  9.      });  
  10. });  
The document.ready occurs when the Document Object Model (DOM) has loaded. This event takes place after the document is ready for execution. This means that all functions and sub-events can be placed inside this event to start the execution.
 
The above code inside the ready event calls a function that will enable a slider object to change its value when an event of its bar movement occurs. That means, when the bar on the slider is moved, the value in number for the slider changes accordingly. Therefore, the jQuery plugin function is initializing here in case of slider object with its sliding value upon another action event.
 
How to create custom Directive?
 
Any jQuery plugin requires a directive to ensure that the code is more usable than what can be used to create a custom directive,
  1. app.directive('directiveName'function() {  
  2.     return {  
  3.         restrict: 'A',  
  4.         link: function(scope, element, attrs) {  
  5.             $(element).pluginInitFunction(params);  
  6.         }  
  7.       };  
  8. });  
The directive is looking for a matching Attribute (A). Although, restrict can take either of the 4 values E, A, C or M, it can also make combinations such as CA, EC, CM, etc.
 
Followed by this, if there are many objects in the scope, the link function links each of the element with scope based on attributes matched. Further, each individual object/element is initialized to a certain parameter.
 
This entire process is the custom directive creation in AngularJS. This particular code for directive addresses the one side path i.e. linking directive to the plugin. But in order to ensure bidirectional path, that is if you want to ensure that any change in scope inside the plugin can be addressed by the directive, then we need to establish two-way binding through ‘$scope.$apply()’ method. This hooks the complete AngularJS cycle with every small manipulation of the plugin scope properties.
 
Merge the jQuery plugin into Custom Directive 
 
After creating a jQuery plugin and a custom directive, now it requires that we merge the two. It can be done by putting the plugin initialization code inside the link() function of the directive.
 
In the above custom directive creation code, when the restriction is applied, a certain template is built upon the console, that inserts the jQuery plugin values to the directive. A certain scope is customized based on the values achieved. This follows the compilation process that compiles all the jQuery plugin data with the custom directive data. After the completion of linking, the entire directive is then placed inside the HTML for syntax completion.
 
Finally, linking the two with the HTML and CSS, creates a workable environment for the jQuery plugin with the help of the AngularJS custom directive. Following is an example of a simple case study:
  1. var app = angular.module('myapp', []);  
  2. app.controller('myController', ['$scope'function($scope) {  
  3.   $scope.sliderValue = 30;  
  4. }]);  
  5. app.directive('mySlider'function() {  
  6.   return {  
  7.     restrict: 'A',  
  8.     scope: {  
  9.       'model''='  
  10.     },  
  11.     link: function(scope, elem, attrs) {  
  12.       $(elem).slider({  
  13.         value: +scope.model,  
  14.         slide: function(event, ui) {  
  15.           scope.$apply(function() {  
  16.             scope.model = ui.value;  
  17.             });  
  18.            }  
  19.          });  
  20.        }  
  21.       };  
  22.  });  
AngularJS at the moment is quite popular. But something is lacking in it that can be made up with the use of jQuery plugins. But being two different languages, it is quite difficult to connect. Using AngularJS directives, the plugins of jQuery can be used quite effectively in the code ensuring that, the driving engine (directive code) is definitely reusable in future as well as repeatable. Directives are ready-made and available but can also be created custom as per your need. It’s the use that defines the nature of the directives.

Comments

Popular posts from this blog

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...

Extension methods in C#

Consider the class C# 1 2 3 4 5 6 7 8 9 10 11 12 13          namespace ExtensionMethod      {          public class testClass {              public string sayHello ( ) {              return "Hello" ;            }        }      }     Invoke the above from your form using C# 1 2 3 4 5 6          testClass test = new testClass ( ) ;      MessageBox . Show ( test . sayHello ( ) ) ;     This will show “Hello” in message box. Consider the scenario where you don...

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome...