Angularjs

Correct Way To Integrate JQuery Plugins In AngularJS

Posted by Weston Ganger on May 15, 2015

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:


<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:


Posted in Angular and Tagged with angularjs jquery plugin directive 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts