Angular JS Problemsss [duplicate] - angularjs
I am writing a sample application using angularjs. i got an error mentioned below on chrome browser.
Error is
Error: [ng:areq] http://errors.angularjs.org/1.3.0-beta.17/ng/areq?p0=ContactController&p1=not%20a%20function%2C%20got%20undefined
Which renders as
Argument 'ContactController' is not a function, got undefined
Code
<!DOCTYPE html>
<html ng-app>
<head>
<script src="../angular.min.js"></script>
<script type="text/javascript">
function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}
</script>
</head>
<body>
<h1> modules sample </h1>
<div ng-controller="ContactController">
Email:<input type="text" ng-model="newcontact">
<button ng-click="add()">Add</button>
<h2> Contacts </h2>
<ul>
<li ng-repeat="contact in contacts"> {{contact}} </li>
</ul>
</div>
</body>
</html>
With Angular 1.3+ you can no longer use global controller declaration on the global scope (Without explicit registration). You would need to register the controller using module.controller syntax.
Example:-
angular.module('app', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
or
function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);
It is a breaking change but it can be turned off to use globals by using allowGlobals.
Example:-
angular.module('app')
.config(['$controllerProvider', function($controllerProvider) {
$controllerProvider.allowGlobals();
}]);
Here is the comment from Angular source:-
check if a controller with given name is registered via $controllerProvider
check if evaluating the string on the current scope returns a constructor
if $controllerProvider#allowGlobals, check window[constructor] on the global window object (not recommended)
.....
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
Some additional checks:-
Do Make sure to put the appname in ng-app directive on your angular root element (eg:- html) as well. Example:- ng-app="myApp"
If everything is fine and you are still getting the issue do remember to make sure you have the right file included in the scripts.
You have not defined the same module twice in different places which results in any entities defined previously on the same module to be cleared out, Example angular.module('app',[]).controller(.. and again in another place angular.module('app',[]).service(.. (with both the scripts included of course) can cause the previously registered controller on the module app to be cleared out with the second recreation of module.
I got this problem because I had wrapped a controller-definition file in a closure:
(function() {
...stuff...
});
But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:
(function() {
...stuff...
})();
Note the () at the end.
I am a beginner with Angular and I did the basic mistake of not including the app name in the angular root element. So, changing the code from
<html data-ng-app>
to
<html data-ng-app="myApp">
worked for me. #PSL, has covered this already in his answer above.
I had this error because I didn't understand the difference between angular.module('myApp', []) and angular.module('myApp').
This creates the module 'myApp' and overwrites any existing module named 'myApp':
angular.module('myApp', [])
This retrieves an existing module 'myApp':
angular.module('myApp')
I had been overwriting my module in another file, using the first call above which created another module instead of retrieving as I expected.
More detail here: https://docs.angularjs.org/guide/module
I just migrate to angular 1.3.3 and I found that If I had multiple controllers in different files when app is override and I lost first declared containers.
I don't know if is a good practise, but maybe can be helpful for another one.
var app = app;
if(!app) {
app = angular.module('web', ['ui.bootstrap']);
}
app.controller('SearchCtrl', SearchCtrl);
I had this problem when I accidentally redeclared myApp:
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);
After the redeclare, Controller1 stops working and raises the OP error.
Really great advise, except that the SAME error CAN occur simply by missing the critical script include on your root page
example:
page: index.html
np-app="saleApp"
Missing
<script src="./ordersController.js"></script>
When a Route is told what controller and view to serve up:
.when('/orders/:customerId', {
controller: 'OrdersController',
templateUrl: 'views/orders.html'
})
So essential the undefined controller issue CAN occur in this accidental mistake of not even referencing the controller!
This error might also occur when you have a large project with many modules.
Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".
app.js
angular
.module('thisApp', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
index.html
<html>
<body ng-app='thisApp' ng-controller='ContactController>
...
<script type="text/javascript" src="assets/js/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
If all else fails and you are using Gulp or something similar...just rerun it!
I wasted 30mins quadruple checking everything when all it needed was a swift kick in the pants.
If you're using routes (high probability) and your config has a reference to a controller in a module that's not declared as dependency then initialisation might fail too.
E.g assuming you've configured ngRoute for your app, like
angular.module('yourModule',['ngRoute'])
.config(function($routeProvider, $httpProvider) { ... });
Be careful in the block that declares the routes,
.when('/resourcePath', {
templateUrl: 'resource.html',
controller: 'secondModuleController' //lives in secondModule
});
Declare secondModule as a dependency after 'ngRoute' should resolve the issue. I know I had this problem.
I was getting this error because I was using an older version of angular that wasn't compatible with my code.
These errors occurred, in my case, preceeded by syntax errors at list.find() fuction; 'find' method of a list not recognized by IE11, so has to replace by Filter method, which works for both IE11 and chrome.
refer https://github.com/flrs/visavail/issues/19
This error, in my case, preceded by syntax error at find method of a list in IE11. so replaced find method by filter method as suggested https://github.com/flrs/visavail/issues/19
then above controller not defined error resolved.
I got the same error while following an old tutorial with (not old enough) AngularJS 1.4.3. By far the simplest solution is to edit angular.js source from
function $ControllerProvider() {
var controllers = {},
globals = false;
to
function $ControllerProvider() {
var controllers = {},
globals = true;
and just follow the tutorial as-is, and the deprecated global functions just work as controllers.
Related
Angular has deprecated the declaration of ng-app without name
Consider the piece of code below: part of html file: <body ng-app> <div ng-controller="MainCtrl">{{name}}</div> </body> part of js file: function MainCtrl($scope) { $scope.name = "John"; } I always put my controllers in some module, whose name I define in ng-app. How it works when I don't define any module ? I just started with angular js and faced the above scenerio.
Declare your app in the DOM with a name: <html ng-app="myApp"> Next, register your app as a module in your JavaScript: angular.module("myApp", []); Note the array as the 2nd argument; this means you're registering a new module, rather than accessing a previously defined module. Finally, register your controller(s) onto your app: angular.module("myApp") .controller("MyCtrl", ["$scope", function($scope) { // controller code goes here }]); Note the lack of the 2nd argument this time, as you're getting the previously defined myApp module. Your question is answered in the 2nd step of the Angular tutorial. If you're new to Angular, I suggest you start here (at step_00).
"Partial Template" Error: Argument 'MyController' is not a function, got undefined
I am getting the above error within a partial template loaded into the main html. When I declare the controller as global it works (MyController1), also when I declare the controller directly within "app.controllers" it works, but when I declare the controller (MyController) as part of the partial template the above error appears. Any help? Code <div ng-controller='MyController1'> <span ng-bind="mydesc"></span> </div> <script type="text/javascript"> function MyController1($scope) { $scope.mydesc = "Direct Global Definition"; console.log('in Direct'); } angular.module('app.controllers').controller('MyController',['$scope',function($scope) { $scope.mydesc = "Defined as part of Controller Inline"; }]); </script> The above code works, but when I change ng-controller="MyController1" to ng-controller="MyController", the error appears. I don't want to use global functions and I can't add every partial controller to "app.controllers".
Looks, like you use angular 1.3 version. In that version global functions as controllers were disabled according to release notes, but still, you're able to use them. All you need to do is to configure controller provider to allow global methods to be used as controllers. Here is full working code <div ng-app="app.controllers" ng-controller="MyController1"> <span ng-bind="mydesc"></span> </div> Though it's not recommended to use global methods. function MyController1($scope) { $scope.mydesc = "Direct Global Definition"; } app = angular.module('app.controllers', []); app.config(['$controllerProvider', function($controllerProvider) { $controllerProvider.allowGlobals(); }]); app.controller('MyController', ['$scope', function ($scope) { $scope.mydesc = "Regular definition"; }]);
AngularJS Big Issue 1.1.5 Upgrade to 1.3.8 (must be simple) :/
I have absolutely no clue anymore what could be wrong here. Using the Version 1.1.5 everything works flawless. <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script> Upgrading to 1.3.8 screws my whole application. <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script> Getting this error Argument 'ContactControllerHeading' is not a function, got undefined .html <html ng-app="myApp" > <body> <div ng-controller="ContactControllerHeading"> ... lots of cool stuff here :) </div> </body> </html> .js var myApp = angular.module('myApp', []); function ContactControllerHeading($scope,$http) { $scope.Home = function() { ... lots of cool stuff :) } }
There's a breaking change in Angular 1.3: you no longer can create controllers using global function (function not associated with any module) Just a minor change, instead of defining controller in global scope, just define it in your app: myApp.controller("ContactControllerHeading", function ($scope, $http) { //controller code });
Angular 1.3 no longer supports functions to stand as controllers by default. See $controllerProvider.allowGlobals() (ref). You will have to call this function from a module config() function to enable this feature. Or better, convert your code to the current practice of using angular.module(...) .controller('ContactControllerHeading', ['$scope','$http',function($scope,$http){...}]);
AngularJS: Service in different file
I'm learning AngularJS following an organization inspired by ng-boilerplate. I create different Angular modules for the different parts of my site. However, I want to create all common elements (services and directives) under the main module, while having them all be in separate source files. This code works, but is the module in sessionService.js referencing the same module than app.js, or is it creating a new one with the same name? app.js var app = angular.module('myApp', [...]) .config(...) .controller(...); sessionService.js angular.module('myApp', []) .service('SessionService', function() { ... });
If you call angular.module('myApp', []) multiple times on the same page, you will likely run into errors or conflicts. I never tried that. However, if you already run angular.module('myApp', []) once. Then you can run angular.module('myApp') (note: without []) to retrieve (refer to) the myApp module you defined earlier.
in controller.js file : var app = angular.module('myApp',['newService']); in service.js : angular.module('newService',[]) .service('someService',function(){ return { // return something return null } } }); Do not forget to include both the js files in your HTML: <script src="controllers/controller.js" type="text/javascript"></script> <script src="services/service.js" type="text/javascript"></script>
Naming & namespacing is important in any project. Try: app.js: var app = angular.module('myApp', ['sessionService', ...])...; sessionService.js: angular.module('sessionService', []) .service('SessionService', ...); Notice that the module name is in lower camel case while the service object itself is upper camel case. This will help you avoid namespace clashing. Hope that helps.
Error: Argument is not a function, got undefined
Using AngularJS with Scala Play, I'm getting this error. Error: Argument 'MainCtrl' is not a function, got undefined I'm trying to create a table consisting of the days of the week. Please take a look at my code. I had checked the name of the Controller, but that seems correct. Note: Code used from this SO answer index.scala.html #(message: String) #main("inTime") { <!doctype html> <html lang="en" ng-app> <head> <link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")"> </head> <div ng-controller="MainCtrl"> <table border="1"> <tbody ng-repeat='(what,items) in data'> <tr ng-repeat='item in items'> <td ngm-if="$first" rowspan="{{items.length}}">{{what}}</td> <td>{{item}}</td> </tr> </tbody> </table> </div> </html> } MainCtrl.js (function() { angular.module('[myApp]', []).controller('MainCtrl', function($scope) { $scope.data = { Colors: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] } }); }());
Remove the [] from the name ([myApp]) of module angular.module('myApp', []) And add ng-app="myApp" to the html and it should work.
FIRST. check if you have correct controller in the route definitions, same as the controller names that you are defining communityMod.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/members', { templateUrl: 'modules/community/views/members.html', controller: 'CommunityMembersCtrl' }). otherwise({ redirectTo: '/members' }); }]); communityMod.controller('CommunityMembersCtrl', ['$scope', function ($scope) { $scope.name = 'Hello community'; }]); different controller names in this example will lead to errors, but this example is correct SECOND check if you have imported your javascript file: <script src="modules/community/controllers/CommunityMembersCtrl.js"></script>
I had the same error message (in my case : "Argument 'languageSelectorCtrl' is not a function, got undefined"). After some tedious comparison with Angular seed's code, I found out that I had previously removed a reference to the controllers module in app.js. (spot it at https://github.com/angular/angular-seed/blob/master/app/js/app.js) So I had this: angular.module('MyApp', ['MyApp.filters', 'MyApp.services', 'MyApp.directives']) This failed. And when I added the missing reference: angular.module('MyApp', ['MyApp.filters', 'MyApp.services', 'MyApp.controllers', 'MyApp.directives']) The error message disappeared and Angular could instanciate the controllers again.
Some times this error is a result of two ng-app directives specified in the html. In my case by mistake I had specified ng-app in my html tag and ng-app="myApp" in the body tag like this: <html ng-app> <body ng-app="myApp"></body> </html>
This seriously took me 4 HOURS (including endless searches on SO) but finally I found it: by mistake (unintentionally) I added a space somewhere. Can you spot it? angular.module('bwshopper.signup').controller('SignupCtrl ', SignupCtrl); So ... 4 hours later I saw that it should be: angular.module('bwshopper.signup').controller('SignupCtrl', SignupCtrl); Almost impossible to see with just the naked eye. This stresses the vital importance of revision control (git or whatever) and unit/regression testing.
I have encountered the same problem and in my case it was happening as a result of this problem: I had the controllers defined in a separate module (called 'myApp.controllers') and injected to the main app module (called 'myApp') like this: angular.module('myApp', ['myApp.controllers']) A colleague pushed another controller module in a separate file but with the exact same name as mine (i.e. 'myApp.controllers' ) which caused this error. I think because Angular got confused between those controller modules. However the error message was not very helpful in discovering what is going wrong.
In my case (having an overview page and an "add" page) I got this with my routing setup like below. It was giving the message for the AddCtrl that could not be injected... $routeProvider. when('/', { redirectTo: '/overview' }). when('/overview', { templateUrl: 'partials/overview.html', controller: 'OverviewCtrl' }). when('/add', { templateUrl: 'partials/add.html', controller: 'AddCtrl' }). otherwise({ redirectTo: '/overview' }); Because of the when('/' route all my routes went to the overview and the controller could not be matched on the /add route page rendering. This was confusing because I DID see the add.html template but its controller was nowhere to be found. Removing the '/'-route when case fixed this issue for me.
If you are in a submodule, don't forget to declare the module in main app. ie : <scrip> angular.module('mainApp', ['subModule1', 'subModule2']); angular.module('subModule1') .controller('MyController', ['$scope', function($scope) { $scope.moduleName = 'subModule1'; }]); </script> ... <div ng-app="mainApp"> <div ng-controller="MyController"> <span ng-bind="moduleName"></span> </div> If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.
Уmed's second point was my pitfall but just for the record, maybe it's helping someone somewhere: I had the same problem and just before I went nuts I discovered that I had forgotten to include my controller script. As my app is based on ASP.Net MVC I decided to keep myself sane by inserting the following snippet in my App_Start/BundleConfig.cs bundles.Add(new ScriptBundle("~/app").Include( "~/app/app.js", "~/app/controllers/*.js", "~/app/services/*.js" )); and in Layout.cshtml <head> ... #Scripts.Render("~/app") ... </head> Now I won't have to think about including the files manually ever again. In hindsight I really should have done this when setting up the project...
I got sane error with LoginController, which I used in main index.html. I found two ways to resolve: setting $controllerProvider.allowGlobals(), I found that comment in Angular change-list "this option might be handy for migrating old apps, but please don't use it in new ones!" original comment on Angular app.config(['$controllerProvider', function($controllerProvider) { $controllerProvider.allowGlobals(); }]); wrong contructor of registering controller before LoginController.$inject = ['$rootScope', '$scope', '$location']; now app.controller('LoginController', ['$rootScope', '$scope', '$location', LoginController]); 'app' come from app.js var MyApp = {}; var app = angular.module('MyApp ', ['app.services']); var services = angular.module('app.services', ['ngResource', 'ngCookies', 'ngAnimate', 'ngRoute']);
I had the same error with a big mistake: appFormid.controller('TreeEditStepControlsCtrl', [$scope, function($scope){ }]); You see ? i forgot the '' around the first $scope, the right syntax is of course: appFormid.controller('TreeEditStepControlsCtrl', ['$scope', function($scope){ }]); A first error i didn't see immediatly was: "$scope is not defined", followed by "Error: [ng:areq] Argument 'TreeEditStepControlsCtrl' is not a function, got undefined"
In my case it was a simple typo in index.html: <script src="assets/javascript/controllers/questionssIndexController.js"></script> that should have been <script src="assets/javascript/controllers/questionsIndexController.js"></script> without the extra s in the controller's name.
Could it be as simple as enclosing your asset in " " and whatever needs quotes on the inside with ' '? <link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")"> becomes <link rel="stylesheet" media="screen" href="#routes.Assets.at('stylesheets/main.css')"> That could be causing some problems with parsing
To fix this problem, I had to discover that I misspelled the name of the controller in the declaration of Angular routes: .when('/todo',{ templateUrl: 'partials/todo.html', controller: 'TodoCtrl' })
Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.
Because this pops-up in Google when trying to find an answer to: "Error: Argument '' is not a function, got undefined". It's possible that you are trying to create the same module twice. The angular.module is a global place for creating, registering and retrieving AngularJS modules. Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module Source: https://docs.angularjs.org/api/ng/function/angular.module#overview Example: angular.module('myApp', []) Is used to create a module without injecting any dependencies. angular.module('myApp') (Without argument) is used to get an existing module.
There appear to be many working solutions suggesting the error has many actual causes. In my case I hadn't declared the controller in app/index.html: <scipt src="src/controllers/controller-name.controller.js"></script> Error gone.
I know this question is old and AngularJS is on its way out, but I want to add my answer anyway. In my case, I created a new file in Visual Studio Code but did not add the .js extension to my controller file name. That is what led to this error for me.