简体   繁体   中英

The controller with name is not registered when loading the html through template

I am currently trying to change my web app from routing through mvc to SPA, where all different will be loaded in single main page. For this I am using ngview directive. This is the main page -

<div ng-app="app">
     <div ng-view>
    </div>
</div>

@section Scripts{
    <script src="~/Scripts/angular-route.js"></script>
    <script>
       var app=angular.module('app',['ngRoute']);

        app.config(function ($routeProvider,$locationProvider) {
            $routeProvider
            .when("/", {
                templateUrl: "Experimental/Index.html",
                controller:"AddressList"

            })

        });

</script>

}

For now I only have one route. my controller is defined in a script tag inside the Index.html file itself and not in a seperate.js file like so -

  angular.module('app')
    .controller('AddressList', ['$scope', '$http', function ($scope, $http) {

        $scope.model = [];
        $http.get('/Addresses/GetAddresses').then(function (response) {
            if (response != null || response != "undefined") {
                $scope.model = response.data;
            }
        });

    }]);

But after load of the main page I am getting an error message -

The controller with name 'AddressList' is not registered.

Does this mean I have to keep all my controllers in seperate files or inside the main html?

We have 2 reasons to not registered message in Angularjs:

  1. The source is not defined in your app

    <script defer src="angular.js"></script> <script defer src="app.js"></script> <.-- app.module(...) --> <script defer src="controller.js"></script> <.-- app.controller(...) -->
  2. Register controller in your app config, this happens when you load controllers as lazy

Note: Not different if you have a separate file for your controller or inline script

var app = angular.module("app", []);
app.config(function($controllerProvider){
    app.controller = $controllerProvider.register;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM