2

I'm learning AngularJS and in all tutorials and screencasts I always saw to use angular writing code all in a unique file, example directives, controllers, factories etc...

Logically for large applications, you will split out the code, make it maintainable and flexible in multiple files and also we should be careful about how many <script> tags we have to require to let our JavaScript files run correctly.

I would like to know which is the best practice to require files when needed, importing less javascript files possible in my view. I took a look at RequireJs but it seems a bit complicated to use it. Is there some tool more efficient and easy to use? Or any good resource to get started?

A small example can be that I have a sort of plugin that has been built using directives, controllers and factories:

app-|
    --Controllers
         |_ pluginController.js

    --Directives
         |_ pluginDirective.js

    --Factories
         |_ pluginFactory.js  

Instead of requiring all three files how do you make it work?

William
  • 443
  • 4
  • 15
Fabrizio Fenoglio
  • 5,767
  • 14
  • 38
  • 75

3 Answers3

1

Here' a great example of how to use RequireJS and AngularJS together. It's a fork of the Angular Seed project and it should hopefully point you in the right direction. It comes with RequireJS baked right in. I definitely recommend learning RequireJS!

William
  • 443
  • 4
  • 15
  • It's definitely a good resource thanks a lot! But should be something more fast then reqirejs, because I think, using requirejs means create your structure of your application on top of requirejs. You move it out and the application does not work. Make sense? – Fabrizio Fenoglio Aug 18 '14 at 20:48
0

I would advice you to read up on dependency injection in the Angular documentaion. It all depends on how you set things up to be honest. If you want to use your service/factory in your controller then you would add the factory as a dependency in your controller or directive. See example below :

Angular.module('{YOUR MODULE NAME}').controller('{YOUR CONTORLLER NAME}', ['$scope', '{FACTORY NAME}',
function($scope,{FACTORY NAME}) {

}]

To invoke the directive within your controller, you would simply could simple add the directive to your controller template. This is a basic example, to learn more read about dependancy injectioninvoke

ramesh
  • 2,296
  • 4
  • 19
  • 29
  • 2
    The dependency injection mechanism still requires all files to be loaded, or the injector will fail to find modules and components. It will not help the OP. – Hugo Wood Aug 18 '14 at 19:46
0

To be clear that I understand - e.g. I want to use "angularFileUpload" module, I need to add it to my module dependency list -

angular .module('kids', ['angularFileUpload' ])

and load the script?

<script src="angularjs/plugins/angular-file-upload/angular-file-upload.min.js" type="text/javascript"></script>

Thanks for help.