Controller Not a Function Error in AngularJS: Comprehensive Guide to Resolving the Issue
When working with AngularJS, you may encounter an error stating that a controller is not a function. This error typically occurs when attempting to define controllers globally, which is no longer allowed in AngularJS 1.3 . To resolve this issue, you must register controllers explicitly using the module.controller syntax.
Solution 1: Register Controllers Using the module.controller Syntax
To define a controller using the module.controller syntax, follow these steps:
angular.module('app', []) .controller('ContactController', ['$scope', function ContactController($scope) { // Controller logic here }]);
Solution 2: Using $inject Annotation and AngularJS 1.3.5
For AngularJS versions 1.3.5 and later, you can use the $inject annotation to define the dependencies for your controller. This annotation should be placed at the top of your controller function.
function ContactController($scope) { $scope.contacts = ["[email protected]", "[email protected]"]; $scope.add = function() { $scope.contacts.push($scope.newcontact); $scope.newcontact = ""; }; } ContactController.$inject = ['$scope']; angular.module('app', []).controller('ContactController', ContactController);
Re-enable Global Controllers (Optional)
AngularJS 1.3 enforces strict scoping, which prohibits global controller declaration. However, you can re-enable global controllers by using the allowGlobals option in your module configuration:
angular.module('app') .config(['$controllerProvider', function($controllerProvider) { $controllerProvider.allowGlobals(); }]);
Additional Considerations:
By following these solutions, you will successfully resolve the "Controller not a function" error in AngularJS and define controllers effectively.
The above is the detailed content of Why is my AngularJS Controller Not a Function, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!