Skip to content

Instantly share code, notes, and snippets.

@BrainCrumbz
Created June 18, 2013 19:24
Show Gist options
  • Save BrainCrumbz/5808422 to your computer and use it in GitHub Desktop.
Save BrainCrumbz/5808422 to your computer and use it in GitHub Desktop.
Reusing an AngularJS Directive core code. The idea is to: 1. conceal the actual directive behaviour in a separate JS "class", 2. store that in an Angular Module value, 3. inject that value into an Angular directive, and then 4. just have the directive factory function return the constructed instance of the "class".
// Define core directive code + attributes and store that as a module value
angular.module('com.namespace.directives').value('MyDirectiveCore', MyDirectiveCore);
function MyDirectiveCore($compile) {
this.restrict = 'A';
this.priority = 10;
this.link = postLink;
return this;
function postLink(scope, element, attrs) {
// Use $compile, scope, element, ... whatever
}
}
// Define directive to be used in HTML, injecting core definition from previous module
angular.module('com.namespace.directives').directive('myDirective', ['$compile', 'MyDirectiveCore', factory]);
function factory($compile, MyDirectiveCore) {
return new MyDirectiveCore($compile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment