0

Sceneraio

I want to load my AngularJS controllers automatically without having to manually include them in the main html file so that when I reference them in my route config file they will successfully register.

How do I auto load the controllers in the simplest way possible without adding too much complexity?

Directory Structure / Code

Directory Structure

Bottom Contents of index.html (index.php to be exact)

...
<script src="app/app.js"></script>
<script src="app/route-config.js"></script> 
</body>
</html>

app.js

angular.module('Main', ['ui.router', 'datatables', 'ngResource'])
    .controller('MainController', function(){
});  


angular.module('Action', ['Main']); 

route-config.js

angular.module('Main').config(config);

function config($stateProvider, $urlRouterProvider)
{
    $urlRouterProvider
        .when('action', 'action')
        .when('issue',  'issue')
        .when('lesson', 'lesson')
        .when('opportunity', 'opporutnity')
        .when('risk', 'risk')
        .otherwise('main');


    $stateProvider
        .state('main', {
            url: "/main",
            //templateUrl: '/app/tool/home/home.html',
            controller: 'MainController'    
        });

     $stateProvider
        .state('action', {
            url: "/actionitems",
            templateUrl: '/app/tool/action/ActionItems.html',    
            controller: 'ActionController'  
        })

     $stateProvider
        .state('action.summary', {
            url: "/actionitems/all",
            templateUrl: '/app/tool/action/ActionItems.html',
            controller: 'ActionController'    
        })     
}

ActionController.js

angular.module('Action')
    .controller('ActionController', ActionController);

function ActionController($resource)
{
    $resource('actionitems.json').query().$promise.then(function(actionitems){
        this.all = actionitems;
    });
}
2
  • Thats a loaded question with no easy answer, really... You have to somewhere, somehow tell something to load the javascript files, and the correct answer is more than likely not "oh, just load them all!" because of various reasons including that you probably have external libraries somewhere and those likely have at least a "src" and "dist" folder, with the "dist" folder having at least a non-minified and a minified version of the files. Commented Apr 1, 2019 at 21:14
  • 1
    Bottom line is that this is not recommended for at least the reason that during development you want to have fine-tuned control over what files are added and visibility over what file any error you might have happens in. What you can and should look into are various packaging frameworks, like webpack, that will build a single-file (or at least just a few) javascript package that gets put in your production index.html Commented Apr 1, 2019 at 21:16

2 Answers 2

1

This is a common need for many large projects, where a properly designed project will be broken out into many files for clarity and readability.

To accomplish this, many (including me) use gulp, or grunt to compile the files into one file.

https://gulpjs.com/

These technologies can be configured to watch a folder recursively (with exceptions if desired) and recompile when the file changes. In your application, you need only include the compiled file, which will be updated as you add files and make changes to the original code files.

Sign up to request clarification or add additional context in comments.

1 Comment

I have in fact used gulp in a NodeJS project before not knowing that it was solving this problem. I was challenging my self to create a new project from scratch. My answer below uses ocLazyLoad which seems to solve the issue but requires me to specify the path to the controller js file.
0

Using the following directory structure and code, I modified to use ocLazyLoad.js in my ActionController. But that resulted in leaving the controller (ActionController) to have bare functions in the code.

Directory Structure

Directory Structure

Though the desired outcome is achieved I am wondering if any improvements or corrections can be made.

ActionController.js

function GetActionItems($resource)
{
    return $resource('actionitems.json').query().$promise;
}

route-config.js

function config($stateProvider, $urlRouterProvider)
{
    $urlRouterProvider
        .when('action', 'action')
        .when('issue',  'issue')
        .when('lesson', 'lesson')
        .when('opportunity', 'opporutnity')
        .when('risk', 'risk')
        .otherwise('main');


    $stateProvider
        .state('main', {
            url: "/main",
            //templateUrl: '/app/tool/home/home.html',
            controller: 'MainController'    
        });

     $stateProvider
        .state('action', {
            url: "/actionitems",
            templateUrl: '/app/tool/action/ActionItems.html',    
            controller: 'ActionController'  
        })

     $stateProvider
        .state('action.summary', {
            url: "/actionitems/all",
            templateUrl: '/app/tool/action/ActionItems.html',
            controller: 'ActionController'    
        })     
}

app.js

angular.module('Action', ['datatables', 'ngResource']);                               

var app = angular.module('Main', ['ui.router', 'oc.lazyLoad', 'datatables', 'ngResource', 'Action']);

app.config(['$ocLazyLoadProvider', '$stateProvider', '$urlRouterProvider', function($ocLazyLoadProvider, $stateProvider, $urlRouterProvider){
            config($stateProvider, $urlRouterProvider);
            $ocLazyLoadProvider.config({
                modules: [{
                    name: 'action',
                    files: ['app/tool/action/ActionController.js']
                }]
            });
}]).controller('MainController', function($ocLazyLoad){

}).controller('ActionController', function($ocLazyLoad, $resource, $scope){
      $ocLazyLoad.load(['action']).then(
        function(){
            GetActionItems($resource).then(function(results){
                  $scope.actionitems = results;    
            }); 
        });
});

ActionItems.html

<div ng-controller="ActionController">
   ActionItems
    <table datatables="ng">
         <thead>
            <tr>
                <th>
                    ID
                </th>
                <th>
                    ActionItemTitle
                </th>
                 <th>
                    Criticality
                </th>
                <th>
                    Assignor
                </th>
                <th>
                    Owner
                </th>
                <th>
                    AltOwner
                </th>
                <th>
                    Approver
                </th>
                <th>
                    AssignedDate
                </th>
                <th>
                    DueDate
                </th>
                <th>
                    ECD
                </th>
                <th>
                    CompletionDate
                </th>
                <th>
                    ClosedDate
                </th>
                <th>
                    Team
                </th>
                  <th>
                    Meeting
                </th>
                  <th>
                    Phase
                </th>
                  <th>
                    Source
                </th>
            </tr>
         </thead> 
         <tbody>
            <tr ng-repeat="actionitem in actionitems">
               <td>{{actionitem.id}}</td> 
               <td>{{actionitem.title}}</td> 
               <td>{{actionitem.criticality}}</td>
               <td>{{actionitem.assignor}}</td> 
               <td>{{actionitem.altowner}}</td> 
               <td>{{actionitem.approver}}</td> 
               <td>{{actionitem.assigneddate}}</td> 
               <td>{{actionitem.duedate}}</td> 
               <td>{{actionitem.ecd}}</td> 
               <td>{{actionitem.completiondate}}</td> 
               <td>{{actionitem.closeddate}}</td> 
               <td>{{actionitem.team}}</td> 
               <td>{{actionitem.meeting}}</td> 
               <td>{{actionitem.phase}}</td> 
               <td>{{actionitem.source}}</td> 
            </tr>
         </tbody>     
    </table>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.