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 am new to the Angular world, and currently trying to finalize a clean design for our ASP.NET MVC project whereby each Angular controller is in a separate file. My question is this, is it possible to lazy load the Angular controllers? I am currently struggling with RequireJS. My proof of concept code is as follows:

CSHTML VIEW - Index.cshtml

<script src="~/Scripts/Controllers/mainController.js"></script> 
<div class="row" ng-controller="MainController">
    <div class="col-md-4">
        <span>{{1+1}}</span>

        Message Test: {{testmessage}}
        <button ng-click="ucase()">Upper</button>
</div>

_Layout.cshtml (first line only to show ng-app)

<html ng-app="mainModule">

app.js

var mainModule = angular.module("mainModule", []);

mainController.js

angular.module('mainModule').controller('MainController', ['$scope', function ($scope) {
    $scope.testmessage = "hello world!";
    $scope.ucase = function () {
        $scope.testmessage = angular.uppercase($scope.testmessage);
    }
}]);

How can I get rid of the reference to mainController.js in the Index.cshtml file? Is there a way to lazy load the controller when it is needed? Can RequireJS help with this?

share|improve this question
    
requirejs can be used and I've used in some old projects. However, these days I prefer to use grunt and combine all js in to a single js file which is included in the html. This allows separating controllers, services, directives in to separate files and it avoids use of requirejs. –  Designing the Code Mar 15 at 16:22
    
May be this will help you: ify.io/lazy-loading-in-angularjs –  Cherniv Mar 16 at 6:21

1 Answer 1

up vote 1 down vote accepted

In the end I was able to implement lazy loading of Angular modules in my POC project by using ocLazyLoader:

https://github.com/ocombe/ocLazyLoad

http://plnkr.co/edit/aGxuXMiPgYA0TFc67YL4 (demo)

However, I am still not sure whether we will implement this going forward.

share|improve this answer
    
Don't hesitate to take a new look at ocLazyLoad as it has been greatly improved lately :) –  Olivier Apr 29 at 8:41

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.