Search code examples
angularjsrequirejsangular-ui-routerangular-amd

AngularAMD, Dynamic UI-Router, RequireJS - "Error: 'MyDashboardCtrl' is not a function, got undefined"


Intro:

I recognize that this is really deep and I won't probably get any help here but I have exhausted what seems like the entire Internet for a solution.

The short of it is I want to make my ui-router dynamic, and with that the controllers, WHILE USING REQUIREJS.

I know Dan Wahlin has something similar but he hard codes his controllers in his main.js file and I'd much prefer keep everything related to $state.routes come from a DB, ie. template & controller.

This is the error I am getting:

Error: [ng:areq] Argument 'MyDashboardCtrl' is not a function, got undefined http://errors.angularjs.org/1.2.9/ng/areq?p0=MyDashboardCtrl&p1=not%20aNaNunction%2C%20got%20undefined

I know the problem is that Dashboard controller is not being cached even though it is in the ui-router as the default route.

While the Dashboard.html is appearing, via the ui-view="container", the controller is just not being cached.

enter image description here

main.js:

require.config({

baseUrl: "/app",
paths: {
    'app' : '/app/app',
    'jquery': '/vendor/jquery/dist/jquery.min',
    'angular': '/vendor/angular/angular',
    'angular-bootstrap': '/vendor/angular-bootstrap/ui-bootstrap-tpls.min',
    'angular-breeze': '/vendor/breeze.js.labs/breeze.angular',
    'angular-cookies': '/vendor/angular-cookies/angular-cookies.min',
    'angular-resource': '/vendor/angular-resource/angular-resource.min',
    'angular-route': '/vendor/angular-route/angular-route.min',
    'angular-sanitize': '/vendor/angular-sanitize/angular-sanitize.min',
    'angular-touch': '/vendor/angular-touch/angular-touch.min',
    'angular-ui-router':'/vendor/angular-ui-router/release/angular-ui-router.min',
    'angular-ui-tree':'/vendor/angular-ui-tree/angular-ui-tree.min',
    'angularAMD': '/vendor/angularAMD/angularAMD.min',
    'bootstrap':'/vendor/bootstrap/dist/js/bootstrap.min',
    'breeze':'/vendor/breeze/breeze.min',
    'breeze-directives':'/vendor/breeze.js.labs/breeze.directives',
    'highcharts':'/vendor/highcharts/highcharts',
    'highchartsng':'/vendor/highcharts/highcharts-ng',
    'moment': '/vendor/moment/min/moment.min',
    'ngload': '/vendor/ng-load/ng-load',
    'q': '/vendor/q/q',
    'spin': '/vendor/javascripts/jquery.spin',
    'toastr': '/vendor/toastr/toastr.min',
    'tweenMax':'/vendor/greensock/src/minified/TweenMax.min',
    'underscore':'/vendor/underscore/underscore.min'
},

// Add angular modules that does not support AMD out of the box, put it in a shim
shim: {
    angular: {
        exports: "angular"
    },
    'angularAMD': ['angular'],
    'angular-ui-router':['angular'],
    'highchartsng': {deps:['highcharts']},
    'bootstrap': {deps:['jquery']},
    'toastr': {deps:['jquery']}
},

// kick start application
deps: ['app'] });

app.js:

define(['angularAMD', 'angular-ui-router', 'config/common', 
            'layout/services/dBoardSvc', 'localize/LangSettings.Svc'], 
function (angularAMD, common, dBoardSvc, LangSettingsSvc) {

var $stateProviderRef = null;
var $urlRouterProviderRef = null;

var app = angular.module("anuApp", ['ui.router'])
    /* @ngInject */
    .config(function ($locationProvider, $urlRouterProvider, $stateProvider) {
        $urlRouterProviderRef = $urlRouterProvider;
        $stateProviderRef = $stateProvider;
        $locationProvider.html5Mode(false);
        $urlRouterProviderRef.otherwise('/')
    })
    /* @ngInject */
    .run(function($q, $rootScope, $state, $window, common, dBoardSvc, LangSettingsSvc){
        // set initial current language
        LangSettingsSvc.currentLang = LangSettingsSvc.languages[0];
        dBoardSvc.all().success(function (data) {
            var startUp = undefined;
            angular.forEach(data, function (value) {
                var tmp = 6;
                angular.forEach(value.viewGroups, function (viewGroup, key) {
                    angular.forEach(viewGroup.viewStates, function (viewState, key) {
                        var viewStateUrl = undefined;
                        if (viewState.isStartUp == true && startUp == undefined) {
                            startUp = viewState.name;
                        }

                        if (viewState.url != '0') {
                            viewStateUrl = viewState.name + "/:moduleId";
                        }

                        var state = {
                            "url": viewStateUrl,
                            "parent": viewState.parentName,
                            "abstract": viewState.isAbstract,
                            "views": {}
                        };

                        angular.forEach(viewState.views, function (view) {
                            state.views[view.name] = {
                                controller: view.controllerName,
                                templateUrl: common.appRoot +  view.templateUrl + '.html',
                                controllerUrl: common.appRoot +  view.controllerUrl + '.js'
                            };

                        });
                        $stateProviderRef.state(viewState.name, angularAMD.route(state));
     --------->>>>>>>>>>>>>>>>>  **console.log(state);**
                    });
                });
            });
            $state.go(startUp);
        });
    });
// Bootstrap Angular when DOM is ready    
angularAMD.bootstrap(app);
return app; });

enter image description here

DashboardCtrl:

define(['app'], function (app) {
'use strict';

app.register.controller('MyDashboardCtrl', MyDashboardCtrl);

/* @ngInject */
function MyDashboardCtrl($scope){
    $scope.pageTitle = 'MyDashboardCtrl';
}; 

});

Conclusion:

Could this be some time of resolve issue? I am literally grasping for straws here and any help would be appreciated.


Solution

  • The problem was with my controller, below is the correct approach:

    define(['angularAMD'], function (app) {
    'use strict'
    
     /* @ngInject */  
    app.controller('MyDashboardCtrl', MyDashboardCtrl);
    function MyDashboardCtrl($scope) {
        $scope.pageTitle = 'This controller now loads dynamically';
    };
    
    // MyDashboardCtrl.$inject = ['$scope']; 
    });
    

    NOTHING is hard coded in my app short of vendor files. My controllers, my views and my services are all dynamic & authorization based!!!

    enter image description here

    I hope this helps others because the implications of being able to utilize requirejs with dynamic routes means that not only does one :

    1. Minimize the javaScript to only that which the view needs, but by coupling it with dynamic views & a login,

    2. One can effectively hide all client side scripts that a respective user may not have authority to acccess.

    I just wish examples were more than 'Hello World' these days ;(