Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularJS routing and loading controllers on demand using requirejs

I'm trying to use AngularJS and RequireJS in combination. I would like to use the $routeProvider service and avoid having to load all the controllers for my views on application startup. For that, I tried the following:

define(['require', 'angular', 'appModule'], function (require, angular, app) {
    app.config(['$routeProvider', function($routeProvider) {
      $routeProvider
          .when('/sites', {templateUrl: '/Site/GetSitesView', controller: function() {
            require(['sitesController'], function(SitesController) {
                return new SitesController();
            })
        }})
    }]);
});

Unfortunately, that did not work for me. There are no errors. The JS file containing the controller is being loaded properly but I cannot see the data bound value in the rendered view. I was wondering whether I could assign the value of controller in some other way that would wait for the asynchronous call (to load the JS file) to complete.

Any ideas?

like image 409
Kassem Avatar asked Mar 01 '13 10:03

Kassem


1 Answers

You can find the solution here

You need to define a resolve property on each route and assign it a function that returns a promise. The function can dynamically load the script contains the target controller and resolve the promise once the loading is complete. In this article, Dan Wahlin shows how to use convention over configuration to have more practical routing.

like image 186
Alborz Avatar answered Sep 28 '22 03:09

Alborz