I am trying to reduce code repetition with my directives. I would like to write a helper function that generates the directives instead of defining them manually. Changing the directive definition to something like:
mydirectiveBuilder(function myButton(){
return {
scope: {
toggle: "@pressed"
}
};
});
I am not sure where this should go (other then hanging it off window). Does angular provide a place for these sorts of methods to go?
Angular doesn't provide anything, but uses angular
as a namespace for its own helper functions. You could simply do the same:
var myApp = (function() {
// private function, not visible from the outside
function privateFunction() {
...
}
function mydirectiveBuilder() {
...
// you can use privateFunction here
}
return {
mydirectiveBuilder: mydirectiveBuilder;
};
})();
And in your directives:
myApp.mydirectiveBuilder(function myButton(){
return {
scope: {
toggle: "@pressed"
}
};
});
You could either do what @JB Nizet suggests or if you don't like the idea of exposing something like myApp
to the global scope, you just put the function somewhere and then wrap everything in a closure as a build step.
File: directiveHelpers.js
function myDirectiveBuilder(){
}
File: someDirective.js
myDirectiveBuilder(function myButton(){
return {
scope: {
toggle: "@pressed"
}
};
});
Then as a build step you concat all files and as a final build step you put a closure around it so it essentially becomes:
File: app.js
(function(){
function myDirectiveBuilder(){
}
myDirectiveBuilder(function myButton(){
return {
scope: {
toggle: "@pressed"
}
};
});
})();
This technique is used by Angular itself throughout the code base.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With