"ShouldWorkController" is not a function. Got undefined

When I try to bind a controller to a template using angular-ui-router $ stateProvider, I encountered the following error:

'ShouldWorkController' is not a function. Got undefined.

      

However, when I declare the controller inside the template using the ng controller everything works fine. What could be wrong here?

app.ts

module App {

    var dependencies = [
        MyControllers            
    ]

    function configuration($stateProvider: ng.ui.IStateProvider) {

        $stateProvider
            .state("shouldWork", {
                url: "/shouldWork",
                templateUrl: "app/shouldWork.html"
                controller: "ShouldWorkController" // does not work
           });
    }
}

      

shouldWorkController.ts

module App.MyControllers {

    interface IShouldWorkViewModel {

    }

    class ShouldWorkController implements IShouldWorkViewModel {}

}

      

ShouldWork.html

<div ng-controller="ShouldWorkController as viewModel" us-spinner spinner-key="spinner-1">
                 ^ --- this works nicely

      

+3


source to share


2 answers


This message means that such a controller is "ShouldWorkController"

not being loaded into the main angular module. Make sure you finish logging calls:



module App.MyControllers {    
    ...
    class ShouldWorkController implements IShouldWorkViewModel {}    
}

// we have to register this controller into some module (MyControllers)
// which is also referenced in the main app module
angular.module('MyControllers')
    .controller('ShouldWorkController', App.MyControllers.ShouldWorkController ); 

      

+2


source


I realize this is old, but I came here via google with the same problem, not the first time. Things to check:



  • Export instructions for your controller class. From the code you posted I can see that you don't need an operator export

    for your class ShouldWorkController

    . This may not be a problem in your case, but it is something you should check. I can reproduce this error by removing the export statement from my controller classes.
  • Check if your HTML template exists (if using a UI router). As described in the UI-Router documentation: "Controller will not be created if no template is defined."
  • Register your controllers in the same file as the controller. Some tutorials demonstrate controllers registered in a module file. While this does work, I personally found it more error prone than registering the controller directly in the controller file.
  • Check out the typescript links . Make sure you add typescript links (for example ///<reference path="../app/services/shouldWorkService.ts">

    ) to typescript files that contain any types you link
  • Check that the controller name specified in the $ stateProvider configuration matches.
0


source







All Articles