Angular module config not called - javascript

I'm trying to get my head around AngularJS and ran into a problem.
var myApp = angular.module('myApp', ['myApp.services']);
myApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
console.log('Configuring module "myApp"');
$routeProvider.when('/dashboard', {templateUrl: 'partial/dashboard', controller: DashboardController});
$routeProvider.when('/menu', {templateUrl: 'partial/other', controller: OtherController});
$routeProvider.otherwise({redirectTo: '/dashboard'});
$locationProvider.html5Mode(true);
}]);
To my understanding the configuration function should be called when the module gets loaded. But it does not!
I have the ng-app="myApp" directive on the <body> tag. And scripts loaded just before the body closing tag in the correct order (as far as that matters).
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="services.js"></script>
<script src="controllers.js"></script>
</body>
I'm pretty sure I must be overlooking something trivial here. There should be a message printed to the console. But it remains empty with no errors or warnings whatsoever.
The parts of the app not depending on the routes runs just fine.
Update: simplified version of my service.js
'use strict';
angular.module('myApp', function ($provide) {
$provide.factory('myService', function ($http) {
var service = function () {
...
service implementation
...
};
return new service();
});
});

It seems that the method I used for defining the service was overriding my myApp module.
This is the overriding line
angular.module('myApp', function ($provide) ...
This code simply redefines the myApp module and adds a function to configure that one.
I refactored service.js to this simplified version and it started to work.
var myApp = angular.module('myApp');
myApp.factory('securityService', function () {
return SomeFancyServiceObject();
});

I was missing ng-app="myApp" inside my html tag - and I realized this while reading your question :-)

I usually see routing applied by chaining them together:
$routeProvider
.when('/dashboard', {templateUrl: 'partial/dashboard', controller: DashboardController})
.when('/menu', {templateUrl: 'partial/other', controller: OtherController})
.otherwise({redirectTo: '/dashboard'});
Can't see why yours would not work, but might be worth a go.

Related

Error: $injector:modulerr Module in angular when loading an image

I'm trying to create an carousal from the scratch using Angular. So my html code relevant to the issue is as follows.
<div id = "section1" class = "" ng-app = "sliderApp">
<div class = "sec1_slider" ng-controller = "app">
<div class = "slider_image">
<img ng-src="{{ imageUrlProfile }}" class = "sm_icon">
And I have imported the relevant APIs.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.js"></script>
My Angular Code is as follows.
var application = angular.module('sliderApp', ['ngRoute']);
application.controller('app', function($rootScope, $scope) {
$rootScope.imageUrlProfile = 'slider-img1.png';
});
In the landing page, the image i defined in angular code 'slider-img1.png' is not loading and throws the following error in browser console.
angular.js:4073 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.5/$injector/modulerr?p0=sliderApp&p1=Refere…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.5%2Fangular.min.js%3A16%3A463)
Click here to see the link to the error.
what should I do to load the image ?
Edit : Here you can find the JSFiddle
The issue is that in your config block, you are specifying variables for controllers. But the variables haven't been declared or assigned values:
Take a look at the Plnkr: http://plnkr.co/edit/2kfnAMja5BWgKTWU9FHt?p=preview
var application = angular.module('sliderApp', ['ngRoute']);
application.controller('app', function($rootScope, $scope) {
$rootScope.imageUrlProfile = 'http://www.amaraholisticwellbeing.com/wp-content/uploads/2015/01/Fall-beautiful-nature-22666764-900-562.jpg';
});
application.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/option1', {templateUrl: 'tab1.html'/**, controller: ProfileCtrl**/}).
when('/option2', {templateUrl: 'tab2.html'/**, controller: WorkCtrl**/}).
when('/option3', {templateUrl: 'tab3.html' /**,controller: EduCtrl**/}).
when('/', {templateUrl: 'openingTab.html'}).
otherwise({redirectTo: '/'});
}]);
You can see where I have commented out the controllers. Those variables don't exist in the script given with your fiddle. I chose to use Plnkr because JSFiddle has issues when trying to send normal http requests (https is fine) for the images.

module dependency with ngRoute breaks angular rendering

I am trying to use Mean stack in my website project. I am using ngRoute for routing and I want to add bootstrap carousel to my main page. I am trying to put angular team carousel component from this page.
While I am trying to implement this, I realize as soon as I try to add module dependency ( which is var app = angular.module('myApp', []) ) to my controller , angular breaks (without any error) and nothing appear in page. If I delete, everything is working normal. I assume this is related with routing ?
Project Structure;
-myApp
-node_modules
package.json
server.js
-public
-controllers
-lib
-views
app.js
index.html
app.js ;
(function(){
var app = angular.module('filmSevmem', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({redirectTo:'/main'});
});
})();
MainController.js;
(function(){
var app = angular.module('myApp');
var MainController = function ($scope, $http) {
....... // codes from carousel
.......
app.controller('MainController', MainController);
})();
If I add , [] or ['ngAnimate', 'ui.bootstrap'] or anything to right of 'myApp', nothing work and I get empty page from my localhost. What can cause this problem ? What should I do ? Thank you.
var app = angular.module('myApp'); means get me the module myApp.var app = angular.module('myApp', [listOfDependencies]); means create the module myApp with all of the listed dependencies. So if you put square brackets in app.js AND in mainController.js, then you overwrite the previously created. The simplest solution would be to add ngAnimate and ui.bootstrap in your app.js like this: var app = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap']);
If you don't want to have all your dependencies in your root module, you can make submodules like var controllers = angular.module('myApp.controllers', ['ngAnimate']), and include this in your app.js like var app = angular.module('myApp', ['myApp.controllers']);
Why you are creating two different modules? And even you are not injecting the first module while creating the second.
By no chance your application is gonna work until and unless you code everything using single module or inject one module in another!

How can I have multiple controller files?

SOLVED
So after viewing your responses and making minor changes to my code, I found a simple typo which prevented me to reach the result I was after. So thank you all to helping with where I was going wrong, I've now got the controllers seperated and everything's working as planned!
----
I am currently developing a hybrid mobile application using Cordova, Ionic and AngularJS within Visual Studio 2015. Due to the vast amount of code I have in my single controller.js file, I want to separate the code so I have a .js controller file per template; instead of everything in one file. Unfortunately, I I do not understand how to pull this off (learning AngularJS still). I've done some researched but the majority of examples I have seen show a very simple demo, which I replicate with my own code but it still doesn't work. So I was hoping if someone can give me an insight where I may be going wrong.
File Structure in /www
index.html
/js
app.js
controllers.js
/js/controllers
login.js
sales.js
/templates
login.html
sales.html
/js/app .js
angular.module('main', ['ionic', 'main.controllers', 'chart.js', 'ngCordova', 'ngIOS9UIWebViewPatch', 'angular.filter'])
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('login', {
cache: false,
url: "/login",
templateUrl: "templates/login.html",
controller: "LoginCtrl"
})
.state('sales', {
cache: false,
url: "/sales",
templateUrl: "templates/sales.html",
controller: "SalesCtrl"
})
$urlRouterProvider.otherwise('/login')
$ionicConfigProvider.views.swipeBackEnabled(false);
});
/js/controllers.js
angular.module('main.controllers', ['ionic', 'ngCordova']);
/js/controllers/login.js
angular.module('main.controllers', [])
.controller("LoginCtrl", function ($scope, $state, $cordovaSQLite, $timeout, $ionicPopup, $cordovaDevice, $ionicLoading, $cordovaKeyboard, $cordovaToast) {
$ionicLoading.show({
template: 'Loading...'
});
// DO STUFF
/js/controllers/sales/js
angular.module('main.controllers', [])
.controller("SalesCtrl", function ($scope, $state, $http, $ionicLoading, $cordovaSQLite, $cordovaToast) {
$ionicLoading.show({
template: 'Loading data...'
});
// DO STUFF
Following this structure, I get this error (quote below): https://docs.angularjs.org/error/ng/areq?p0=LoginCtrl&p1=not%20a%20function,%20got%20undefined
Argument 'LoginCtrl' is not a function, got undefined
I managed to get it to work slightly, only when I had login.js and not sales.js, but of course $state.* stopped working when trying to change template. So I know that wasn't 100% either. Hopefully this will make sense, fi it doesn't just clarify what I may be not making sense in, and I shall explain more if need be, appreciate any help. :)
EDIT
index.html
<!-- App references -->
<link href="css/ionic.css" rel="stylesheet" />
<link href="css/angular-chart.css" rel="stylesheet" />
<link href="css/index.css" rel="stylesheet" />
<script src="lib/ionic/ionic.bundle.js"></script>
<script src="lib/ngCordova/ng-cordova.js"></script> <!-- Must be after Ionic but before Cordova-->
<script src="cordova.js"></script>
<script src="scripts/index.js"></script>
<script src="lib/angular-cookies/angular-cookies.min.js"></script>
<script src="lib/angular-chart/Chart.min.js"></script>
<script src="lib/angular-chart/angular-chart.min.js"></script>
<script src="lib/angular-ios9-uiwebview.patch.js"></script>
<script src="lib/angular-filter/angular-filter.min.js"></script>
<script src="js/directives/favourite.js"></script>
<script src="js/controllers.js"></script>
<script src="js/controllers/login.js"></script>
<script src="js/controllers/sales.js"></script>
<script src="js/app.js"></script>
You are redefining your module again & again in your each controller file. Which is clearing out old registered controller from that module.
You have already defined that module in your /js/controllers.js.
angular.module('main.controllers', ['ionic', 'ngCordova']);
So reuse that module in other Javascript files when your are binding any component to it as below.
angular.module('main.controllers')
The best approach is that you clearly separate module creation from module usage.
modules.js:
angular.module('main', ['main.sales']);
angular.module('main.sales', []);
src/sales/scripts/sales-controller.js:
angular.module('main.sales').controller(function() {});
If you concat and minify your js files via grunt or gulp, you should always explicitly include modules.js first, afterwards you can include the rest via a pattern like 'src/**/*.js' for example.
This way the modules are always defined before they are used. If that's not the case, angular will complain about a non existing module.
PS: it's way better to create functional modules (sales related functionality in 1 module) instead of technical modules (all controllers in 1 module)
You are declaring the main.controllers module twice, once for each controller. Also, it's not strictly required to declare a separate module for the controllers, you could just declare the controllers within your main module. Some would argue that you lose reusability - and they would be right - but depending on the size of your project and how tightly coupled your controllers are with your application (90% of the time the answer is: very) you could go that way. Since you are probably just starting out, try doing something like this:
js/app.js
angular.module('main', ['ionic', 'chart.js', 'ngCordova', 'ngIOS9UIWebViewPatch', 'angular.filter'])
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('login', {
cache: false,
url: "/login",
templateUrl: "templates/login.html",
controller: "LoginCtrl"
})
.state('sales', {
cache: false,
url: "/sales",
templateUrl: "templates/sales.html",
controller: "SalesCtrl"
})
$urlRouterProvider.otherwise('/login')
$ionicConfigProvider.views.swipeBackEnabled(false);
});
Note that I am no longer depending on main.controllers? That's because next I'm doing this:
angular.module('main')
.controller("LoginCtrl", function ($scope, $state, $cordovaSQLite, $timeout, $ionicPopup, $cordovaDevice, $ionicLoading, $cordovaKeyboard, $cordovaToast) {
$ionicLoading.show({
template: 'Loading...'
});
// DO STUFF
And this:
angular.module('main')
.controller("SalesCtrl", function ($scope, $state, $http, $ionicLoading, $cordovaSQLite, $cordovaToast) {
$ionicLoading.show({
template: 'Loading data...'
});
// DO STUFF
The different controllers can (and should) be declared each in a separate file, so that you have a clear structure. It might be more correct to have a separate module for the controllers, and I fear my opinion might be unpopular, but I don't really see the point - whereas I strongly urge you to separate your services and your directives into different modules, since it's much more likely that you're going to use them again in other projects.
My suggest we will organize code by split to the module, and inject it in the app.js file
This is detail my way: https://mymai91.github.io/ionic/2016/07/01/ionic-structure-code-for-project.html
Code demo: https://github.com/mymai91/mymaiApp
to anyone looking at the "solved code"...
The Square brackets in the inner controlleres should be removed:
angular.module('main.controllers', [])
-->
angular.module('main.controllers')

AngularJS "Argument 'mainController' is not a function"

im new to Angular and need some help.
I'm trying to setup a basic directory structure where i have modules and controllers in seperate JS-files. However, when i do this i get the error stated in the posts title.
The module looks like this:
var myApp = angular.module('myApp', ['ngRoute']);
Controllers like this:
myApp.controller('mainController', function ($scope) {
$scope.message = 'Test message';
});
And routes:
myApp.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'components/home/home.html',
controller: 'mainController'
})
// route for the about page
.when('/about', {
templateUrl: 'components/about/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl: 'components/contact/contact.html',
controller: 'contactController'
});
});
Then in my HTML i use ng-app="myApp" and ng-controller="mainController" and trying to write out: {{message}} from it. But it doesn't work.
If i put all the angular code in the same JS-file, then it works. But not when they are seperated.
Help and an explaination is highly appreciated!
As the comments have suggested, this error is usually caused my a missing reference to the file that contains your mainController. Your index.html should contain script references to your javascript files. Here is an example from one of my small apps:
<!-- Custom scripts -->
<script src="/app.js"></script>
<!-- Controllers -->
<script src="/login/loginCtrl.js"></script>
<script src="/home/homeCtrl.js"></script>
<!-- Directives -->
<script src="/common/directives/pageHeader/pageHeader.directive.js"></script>
<script src="/common/directives/footerGeneric/footerGeneric.directive.js"></script>
<script src="/common/directives/queryBuilder/queryBuilder.directive.js"></script>
<script src="/common/directives/scroll/infScroll.js"></script>
All of this should come after including jquery and angular. Additionally (I don't know where you include app.js successfully, you may have already done this) you need to direct AngularJS routes to the index.html file from your express server (assuming express/node backend) in your main app file like so:
app.use(express.static(path.join(__dirname, 'app_client')));
app.use(function (req,res){
res.sendfile(path.join(__dirname, 'app_client', 'index.html'))
});
I hope this was helpful. If you post the code where you attempt to include your application and controller then I can provide a more detailed answer.

Uncaught Error: [$injector:modulerr with angualrJs when i use routing

this is part of my problem = https://jsfiddle.net/2vrz38d6/
it contain just the js part open the console to see what i have
i get confused to solve this error
Error: $injector:modulerr
Module Error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.10/$injector/modulerr?p0=myApp&p1=Error%3A%…3A9641%2Fassets%2Fglobal%2Fplugins%2Fangularjs%2Fangular.min.js%3A38%3A435)
My Error happen with routing in angularJs
the error which i took it is :
my Error page here
my code is :
(function () {
var MyApp = angular.module('myApp');
MyApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/expenses.html',
controller: 'CurriculumController'
})
.otherwise({
redirectTo: '/'
});
and the controller
MyApp.controller('CurriculumController', ['$scope', '$rest', function ($scope, $rest) {
//some stuf here
for my script angular file :
in the first i have this
<script src="/assets/global/plugins/angularjs/angular.min.js"></script>
and in the middle of the project i have
the file of my angular apps
<script src="/Scripts/NGModel/Curriculum/Curriculum.js"></script>
and after that the file of the routing part for angularjs
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
As people above have suggested, you need to include that file, but you also need to make sure that you are doing it in the correct order as well in your index file. I suppose trying a different set of CDNs wouldn't hurt either.
<script src="https://code.angularjs.org/1.3.15/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-route.min.js"></script>
Also, in your route configurations, just a mention that you can do this as well for your otherwise:
MyApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/expenses.html',
controller: 'CurriculumController'
})
.otherwise("/");
});
you have to include angular-route.js.
Dependency injection would be angular.module('myApp', ['ngRoute']);
EDIT as the inclusion of Angular libraries were updated in the OP's problem statement :-
Replace
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script> with
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular-route.min.js"></script> as you have mentioned in comments that you are using v1.3.10
And as #Garrett has suggested, add,
.otherwise("/");
You will need to make this work:
1) Add the angular-route file:
Include the file below the angular.js
<script src="angular-route.js">
2) Inject the ng-route at the definition of your app:
angular.module('myApp', ['ng-route']);
you should add your dependencies in to the module like this
var app = angular.module('myApp', ['ngRoute']);

Categories

Resources