Home >Web Front-end >JS Tutorial >Why is my AngularJS Controller undefined, and how can I register it correctly?

Why is my AngularJS Controller undefined, and how can I register it correctly?

DDD
DDDOriginal
2024-12-16 06:07:15735browse

Why is my AngularJS Controller undefined, and how can I register it correctly?

Error in AngularJS: Controller Registration

Question:

When attempting to define controllers globally in an AngularJS application, the error "Controller not a function, got undefined" occurs.

Answer:

As of AngularJS 1.3 , global controller declaration is no longer supported. Controllers must now be registered using the module.controller syntax.

Registration Methods:

  1. Using the .controller() Method:
angular.module('app', []).controller('ContactController', ['$scope', function($scope) {
  // Controller logic
}]);
  1. Using Dependency Injection:
function ContactController($scope) {
  // Controller logic
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);

Alternative: Allow Globals

The use of global controllers can be re-enabled by setting allowGlobals in the $controllerProvider:

angular.module('app').config(['$controllerProvider', function($controllerProvider) {
  $controllerProvider.allowGlobals();
}]);

Additional Considerations:

  • Ensure the ng-app directive is included on the root element of the application.
  • Verify that the correct file is included in the scripts.
  • Avoid defining the same module multiple times, as this can override previously registered entities.

The above is the detailed content of Why is my AngularJS Controller undefined, and how can I register it correctly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Why is visual important?Next article:Why is visual important?