Correct Way To Integrate JQuery Plugins In AngularJS

Posted By Weston Ganger

When you want to use a jquery plugin in AngularJS just make sure you do it correctly.

myApp.directive('directiveName', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      angular.element(element).myPlugin(scope.$eval(attrs.directiveName));

      scope.$on("$destroy", function(){
        // Remove jQuery plugin from element to prevent memory leaks
        // If your plugin doesn't have a remove function its probably not well suited to persistent javascript environments
        element.myPlugin("destroy");
      });
    }
  };
});

And then in your template:
<pre>
<code class="language-markup">
<div directiveName="{width: "220px", placeholder: "Search..."}"></div>
<script type="text/javascript" src="pluginName.js"></script>


The reason we use scope.$eval() in the directive is so that the configuration comes through as a hash, not a string.


Related External Links:

- [Stack Overflow - Correct Way to Integrate jQuery Plugins in AngularJS](http://stackoverflow.com/questions/16935095/correct-way-to-integrate-jquery-plugins-in-angular-js)

Article Topic:Software Development - Javascript

Date:May 15, 2015