Skip to content Skip to sidebar Skip to footer

Can You Use Angular Dependency Injection Instead Of Requirejs?

I'm starting with angular, how could I break alll the code from one app into many files?, I watched the 60ish minutes intro, and they mentioned that I could do this without require

Solution 1:

AngularJS does not currently have a script loader as part of the framework. In order to load dependencies, you will need to use a third party loader such as RequireJS, script.js, etc.

Per the Docs(http://docs.angularjs.org/guide/module#asynchronousloading):

Asynchronous Loading

Modules are a way of managing $injector configuration, and have nothing to do with loading of scripts into a VM. There are existing projects which deal with script loading, which may be used with Angular. Because modules do nothing at load time they can be loaded into the VM in any order and thus script loaders can take advantage of this property and parallelize the loading process.

...or, as @xanadont explained, you can add <script> tags to your page for every file.

Solution 2:

You must have a

<scriptsrc="file.js"></script>

per each file that you're using. It should work once you have all the references in place.

Or ... check out this article for a way to roll-your-own runtime resolution of controllers.

Solution 3:

You've got to separate the idea of downloading from the idea of loading and executing in-memory. Use Yeoman/grunt or similar build tools to manage the process of adding individual files to the project for Angular's various modules controllers, directives, services, etc. that are attached to those modules. Then, at build-time, the files will be minified and concatenated for a speed/bandwidth improvement that's vastly superior to lazy-downloading of individual files.

Once you've dealt with the files, Angular handles the rest, executing dependencies only when they're actually needed.

In the example above, @Jose, your problem was that you're not attaching your dependencies properly to the original module. You're creating new modules and burying the dependencies inside of them. In the first version, you used var app to cache the reference to the module called 'app' and then did app.controller(), etc. So, you're calling the .controller() method on the app module.

But in the second, you still need to attach those dependencies to the main app module. To do that, you need to call angular.module('app') to access the original module, then you can chain a call to .controller() or .directive() from that module, once you've retrieved it.

Bottom-line, use Angular's constructs for the loading of Angular dependencies. If, after you've gotten all of that out of the way, you still want to use Require for loading third-party scripts, go ahead. But I recommend testing first to see if you're actually adding value.

Post a Comment for "Can You Use Angular Dependency Injection Instead Of Requirejs?"