1

Using Angular 1.3.x, global functions are not recognized as controllers. What's going wrong? How do I correct this?

function MyController() {
  // etc
}
<div ng-controller="MyController"></div>

The console shows the following error:

Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined

m59
  • 43,214
  • 14
  • 119
  • 136
  • I overhauled the question for you. This is a helpful thread since this was a breaking change for Angular and many people won't know that. – m59 Mar 22 '15 at 02:44

2 Answers2

3

According to the docs:

If the current $controllerProvider is configured to use globals (via $controllerProvider.allowGlobals()), this may also be the name of a globally accessible constructor function (not recommended).

This change arrived in Angular 1.3.0-beta.15 (changelog).

This is a change in Angular's behavior from older versions, which would recognize global functions as controllers by default. It's bad practice and shouldn't be used anyway. The ironic thing is that in order to use them, you would have to use a proper setup for your app anyway, and wouldn't want to use them at that point anyway.

So, you need to setup your app this way: ng-app="myApp and ng-controller="MyController"

angular.module('myApp', [])
.controller('MyController', function($scope) {
    $scope.author = {
      'name' : 'Mohammad Mohabati',
      'title' : 'Web Design',
      'company' : 'MohabatiPro'
    };
  })
;

allowGlobals could then be set with:

.config(function($controllerProvider) {
  $controllerProvider.allowGlobals();
});

so that ng-controller="SomeFunction" will work with a global function like:

function SomeFunction($scope) { //etc

but don't do it. :)

m59
  • 43,214
  • 14
  • 119
  • 136
0

try initating your module first.
In you HTML add :

ng-app='myApp'

In your script add : var app = angular.module('myApp', []);

Sushrut
  • 1,541
  • 1
  • 12
  • 16