Search code examples
javascriptangularjsyeomanyeoman-generatoryeoman-generator-angular

Using yeoman-generator variable inside generated template


I am generating an angularJS project with yeoman. I call the generator with an argument and I get it from my main generator's script (index.js) by doing:

this.argument('name', { type: String });

I can use this parameter inside this same index.js by using:

this.options.name

Question: I want to use this same this.options.name inside my template, so that i can give its value to a variable. How can I do it?


Solution

  • Define an angular constant and set it to this value. Then inside the controller associated to this view, just inject this constant.

    myApp.constant('YEOMAN_NAME', MYVALUE);
    

    Then just inject your constant inside the controller associated to your view, associate this constant to a scope variable and use it inside your template.

    Now the "hardest" part is how to get this value inside the angular environment.

    I don't know what is your index.js, I suppose that is only the main script associated to your page. In this case, if you do inside the main script something like

    this.myVariable = 'myValue';
    

    You are actually creating a new attribute to the window object (if you are not doing that inside some function)

    So what you could do is to associate this variable to a window parameter, and try to be most specific as possible so you are not on risk to override something else in the window, like:

    window.myYeomanName = this.options.name;
    

    Then you can define your constant inside angular everywhere just doing:

    myApp.constant('YEOMAN_NAME', window.myYeomanName);