Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
5  
The only way to do this is to get hold of $controllerProvider. I have a working solution here: github.com/matys84pl/angularjs-requirejs-lazy-controllers –  matys84pl Mar 1 '13 at 11:45
    
@matys84pl that's actually along the lines of what I was thinking to do. Thanks for sharing this. One thing though, I went through the code and saw that you are loading templates using the Require Text plugin, is that the only supported way of loading templates using your library? What if I want to load the template from a URL on the server, would that work? –  Kassem Mar 1 '13 at 13:10
    
It depends if the url is relative to your app.. in other words is it on the same domain? If not then I think you would have to use some kind of proxy to achive that (to load files from other domain). –  matys84pl Mar 1 '13 at 14:50
    
Thanks matys84pl. This really helped. Just wondering why your reply is not marked as answer (Kassem) ? –  Tiago Reis Apr 15 '13 at 10:26
    
@matys84pl can we use it for services loading also? –  Cherniv Jan 19 '14 at 14:37

1 Answer 1

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.

share|improve this answer
    
Thank you for the post. Helped me a lot! –  VishwaKumar Oct 30 '14 at 7:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.