Load all dependencies dynamically

Asked

Viewed 460 times

3

In the file index php. do the include of all controllers:

<script src="app/app.js"></script>
<script src="app/ctrl_A.js"></script>
<script src="app/ctrl_B.js"></script>
<script src="app/ctrl_C.js"></script>
//etc...

That’s not good, since I’m uploading javascript files that aren’t missing, for example, on the homepage.

In the app . config I am referring to the controller as follows:

app.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', 
function($urlRouterProvider, $stateProvider, $locationProvider) {
    $urlRouterProvider.otherwise("/login");
      $stateProvider
        .state('login', {
            url: "/login",
            templateUrl: "view/login.html",
            controller: 'ctrl_A'
        })
//...

How do I make dependencies (controller, Factory, Directive, ect...) to be dynamically loaded without declaring in index.php?

  • the angular has the concept of single page application (SPA) and has no problem it load all the code right from the start. It has javascript automation tools that bind all your Avascripts and place them in a single file. If you want to load them dynamically you can try using requirejs . a tool that does this for you. As I am not an expert in Angularjs I will wait for someone more experienced answer if the angular already does this.

1 answer

1

I believe the best way is to use the angularAMD. It basically links Angularjs with a definition of asynchronous loading of Javascript modules called AMD, which does just what you expect.

Your index would only be with a script this way:

<script data-main="app/app.js" src="app/libs/require.js"></script>

Turning your code into AMD modules brings benefits to your project’s maintainability is not a difficult task.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.