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
Release: 2024-12-16 06:07:15
Original
737 people have browsed it

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
}]);
Copy after login
  1. Using Dependency Injection:
function ContactController($scope) {
  // Controller logic
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);
Copy after login

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();
}]);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template