Uncaught ReferenceError:Controller is not defined in AngularJS

If you have some AngularJS code like this,

var mailApp = angular.module('myMail', []);

function emailRouteConfig($routeProvider) {
    $routeProvider.when('/', { controller: listController, templateUrl: 'list.html' }).
                   when('/view/:id', { controller: DetailController, templateUrl: 'detail.html' }).
                   otherwise({ redirectTo: '/'});
}


and controller like this,

mailApp.controller('listController',function ($scope) {
    $scope.messages = messages;
})

mailApp.controller('DetailController',function ($scope, $routeParams) {
    $scope.message = messages[$routeParams.id];
})


then this will generate a error in console saying Uncaught ReferenceError: controller is not defined in module.

To overcome this issue there are two solutions.

Solution 1:

The issues is because of this
    $routeProvider.when('/', { controller: listController, templateUrl: 'list.html' }).
                   when('/view/:id', { controller: DetailController, templateUrl: 'detail.html' })


This is telling Angular to point at the listController object, which is undefined and causes an error.

Now, enclose the controller name in quotes like this,

    $routeProvider.when('/', { controller: 'listController', templateUrl: 'list.html' }).
                   when('/view/:id', { controller: 'DetailController', templateUrl: 'detail.html' })


Solution 2:

Define your controllers like this

function listController($scope) {
    $scope.messages = messages;
}

function DetailController($scope,$routeParams) {
    $scope.message=messages[$routeParams.id];
}


No comments:

Post a Comment