noland
noland

Reputation: 125

Argument controller is not a function, got undefined

I am receiving the following error:

Argument 'mainController' is not a function, got undefined

Which is strange because the code worked before I started adding pages and content to the app.

HTML

<!DOCTYPE html>
<html lang="en" id="top" ng-app="myApp">
<head>
 <title>Website</title>

 <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
 <link rel="stylesheet" href="css/main.css"/>

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>

  <script src="js/jquery-1.11.3.min.js"></script>
  <script src="js/main.js"></script>

</head>

<body ng-controller="mainController">

<div class="menu">
    <ul>
        <li><a href="#messages">Messages</a></li>
        <li><a href="#settings">Settings</a></li>
    </ul>
</div>

<div class="wrapper" ng-view></div>

</body>
</html>

JS

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/dashboard.html',
            controller  : 'mainController'
        })

        // route for the settings page
        .when('/settings', {
            templateUrl : 'pages/settings.html',
            controller  : 'settingsController'
        });
});

I started my code from a template.

Upvotes: 0

Views: 64

Answers (1)

David L
David L

Reputation: 33833

You're confusing referencing a controller instance in your html (which binds it) to actually creating your controller within your application.

Declare it off of your root app module.

myApp.controller('mainController', ['$scope', function ($scope) {

}]};

In addition, since you're declaring a template and a controller pair, you cannot bind your controller on the body element. You should instead bind it within it's respective template.

<div class="menu" ng-controller="mainController">
    <ul>
        <li><a href="#messages">Messages</a></li>
        <li><a href="#settings">Settings</a></li>
    </ul>
</div>

If you absolutely want it to be bound to the body element, remove it from your routing declaration.

Upvotes: 1

Related Questions