gingermusketeer gingermusketeer - 4 months ago 16
AngularJS Question

Where do angular helper functions go?

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?

Answer

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"
        } 
    };
});
Comments