Search code examples
javascriptangularjsangular-ui-routerangularjs-controllerangularjs-controlleras

Angular app with ui-router not hitting controller unless its inline function


I am having trouble with ui-router. If I use an inline function it works, otherwise when I click on the route the controller is not used. I can debug the browser and the js is being delivered but no break points are ever touched.

//This is the error when I go to the non working route
Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=Provider%20%3C-%20%20%3C-%20MainCtrl

//The commented main route works
(function(){
angular.module('invNodeServer',[
        'ui.router'

])
    .config(function ($stateProvider,$urlRouterProvider,$locationProvider) {
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
        $urlRouterProvider.otherwise("/");
        $stateProvider
            .state('main', {
                url: "/",
                templateUrl: "app/main/main.html",
                controller:'MainCtrl',
                controllerAs:'vm'
            })
            //.state('main', {
            //    url: "/",
            //    templateUrl: "app/main/main.html",
            //    controller:function($scope){
            //        $scope.title = 'Main'
            //    }
            //})

    })
    })();


// This is the controller for the non working route
(function () {
'use strict';
var controllerId = 'MainCtrl';

angular.module('invNodeServer').controller(controllerId, MainCtrl);

MainCtrl.$inject = [''];

/* @ngInject */
function MainCtrl() {

    /* jshint validthis: true */
    var vm = this;
    vm.title = 'Main';
    vm.activate = activate;

    activate();

    ////////////////

    function activate() {
    }
}
})();

Solution

  • $injector/unpr?p0=Provider states that the dependency for which you are asking isn't register in module.

    That is because you are asking injector to give '' (blank dependency) on this line, so injector doesn't find any dependency on that name(its obvious) & throwing an error of $injector/unpr?p0=Provider.

    MainCtrl.$inject = [''];
    

    For fixing the issue, you should keep it blank like below.

    MainCtrl.$inject = [];