The argument 'ContactsCtrl' is not a function, got undefined

I have a problem in routing and AngularJS controllers. Here is the code:

Index.html

<!DOCTYPE html> <html ng-app="contacts"> <head> <script src="libs/angular.min%20(1).js"></script> <script src="contacts.js"></script> <script src="index.js"></script> <title></title> </head> <body > <div data-ng-view=""></div> </body> </html> 

index.js

 var myApp = angular.module('contacts', []); myApp.config(function ($routeProvider) { $routeProvider .when('/', { controller: 'ContactsCtrl', templateUrl: '/views/show-contacts.html' }) //.when('/view2', { controller: 'MyCont', templateUrl: 'V2.htm' }) .otherwise({ redirectTo: '/' }); }); 

contacts.js

 var myApp = angular.module('contacts', []); myApp.controller('ContactsCtrl', function ($scope) { $scope.name = "omar"; }); 

but I get this error:

The argument 'ContactsCtrl' is not a function, got undefined

Any help?

+6
source share
3 answers

You override your application in index.js , so the controller created in contacts.js will be lost. Remove this line from index.js :

 var myApp = angular.module('contacts', []); 
+10
source

Change your index.html as follows:

 <script src="index.js"></script> <script src="contacts.js"></script> 

And in your contact.js change

var myApp = angular.module('contacts', []); before

 var myApp = angular.module('contacts'); 

Angular module with two arguments, such as angular.module('contacts', []); , will create a new module, but the angular module with a single argument, for example angular.module('contacts'); selects an existing module. Here in this case 'contacts'

+19
source

I would suggest creating two different module names, one in index.js (This will be the name of the application that you would specify in the html attribute of ng-app) and the other in contacts.js (Module name for controllers). In index.js, create dependecy for the contact. Js`. I was able to solve the problem by doing below.

Updated contacts.js Here I updated the contacts to contactsController

 var myApp = angular.module('contactsController', []); myApp.controller('ContactsCtrl', function ($scope) { $scope.name = "omar"; }); 

Updated index.js. Here I have added ContactController as a dependency. It was easier for me to call this as app.js. This way ng-app always maps to the module name in app.js.

  var myApp = angular.module('contacts', [contactsController]); myApp.config(function ($routeProvider) { $routeProvider .when('/', { controller: 'ContactsCtrl', templateUrl: '/views/show-contacts.html' }) //.when('/view2', { controller: 'MyCont', templateUrl: 'V2.htm' }) .otherwise({ redirectTo: '/' }); }); 
+1
source

Source: https://habr.com/ru/post/952274/


All Articles