Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do angular helper functions go?

Tags:

angularjs

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?

like image 665
gingermusketeer Avatar asked Aug 11 '13 10:08

gingermusketeer


2 Answers

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"
        } 
    };
});
like image 124
JB Nizet Avatar answered Sep 28 '22 01:09

JB Nizet


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.

like image 21
Christoph Avatar answered Sep 28 '22 02:09

Christoph