Angular: [$injector:modulerr] Failed to instantiate module - javascript

I've been trying to set up basic AngularJS functionality for a project but have been hitting a brick wall when it comes to including angular-route. Both are version 1.4.8. I'm currently using gulp-require to concatenate my JS, here's my main javascript file
// =require ../components/jquery/dist/jquery.min.js
// =require ../components/angular/angular.js
// =require ../components/angular-route/angular-route.js
$(document).ready(function() {
// =require app/app.js
}); // Doc ready is done!
And my app.js file
var app = angular.module('myApp', ['ngRoute']);
app.controller("ctrl", ["$scope", 'ngRoute', function($scope) {
$scope.test = "It works!";
}]);
I've checked and all the files are concatenating properly. The ng-app and ng-controller attributes are on my HTML file. I've tried adding and removing the ngRoute injection and switching the order of the files but to no avail. It's frustrating since I used Angular 1.4.5 in almost the exact same way without these issues popping up but I can't replicate the same here even when going back. But the {{test}} variable in my HTML is still not rendering, and basic operations like {{2 + 3}} aren't either.
EDIT: here is the link to the original error message I'm currently receiving: http://tinyurl.com/zx3k85f
EDIT 2: The parts of my HTML code that's calling the app and the controller:
<html lang="en" ng-app="myApp">
<body ng-controller="ctrl">
</body>
</html>
I'm using nunjucks for HTML dynamic generation, although I've changed the syntax for this so it doesn't conflict with Angular's double curly braces.

You can't inject module as dependency inside controller, you should remove 'ngRoute' from the controller DI inline array.
app.controller("ctrl", ["$scope", , function($scope) {
Update
Basically the real problem is you are loading your angular component script using requirejs(lazily), so while you are having ng-app="myApp" with module name start looking for myApp module, and the module has not loaded therefore it throws an error .
So I'd recommend you to don't use ng-app directive to start angular on page load. Instead you should wait until all the scripts related to angular loaded, & then to bootstrap angular app lazily using angular.bootstrap method.
Code
$(document).ready(function() {
requirejs(["app/app.js"], function(util) {
angular.bootstrap(document, ['myApp']);
});
});

ngRoute is a provider that needs to be configured in the module config section before being used. Using it within a controller does not make any sense. Here the version that will work:
angular.module('myApp', ['ngRoute']);
angular.module('myApp').controller("ctrl", ["$scope",function($scope) {
$scope.test = "It works!";
}]);
Moreover, you need to call your module using directive ng-app=myapp in the html element where you plan to render your app.

Related

angular module injection error in when running my app

I just started with Angular and I'm little bit confused with this error.
I don't know exactly what I've done wrong, but my console is showing this error:
angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=app&p1=Error%3A%20%…(http%3A%2F%2Flocalhost%3A8080%2Flib%2Fangular%2Fangular.min.js%3A21%3A179)(…)
my html:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<link rel="stylesheet" href="css/app.min.css">
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-route/angular-route.min.js"></script>
<script src="lib/angular-resource/angular-resource.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</head>
<body>
test
</body>
</html>
and my app.js:
(function() {
'use strict';
angular.module('app', [
'ngRoute',
'ngResource',
'mainController'
])
.config(['$routeProvider', function() {
routeProvider.when("/", {templateUrl: 'www/index.html', controller: 'mainController'})
}])
.controller('mainController', function($scope){
alert();
})
})();
what is wrong ?
The mainController is not a module but a controller inside your app module. So injecting mainController does not make sense here. Remove the mainController injection from your modules dependencies array.
The other dependencies, ngRoute and ngResources are modules which your module is depending upon - for eg, $routeProvider is from the ngRoute module, so in order to get routeProvider, you need to inject the ngRoute module as dependency.
You don't have to inject controller as a dependency to the module
Change,
angular.module('app', ['ngRoute','ngResource','mainController'])
To
angular.module('app', ['ngRoute','ngResource'])
DEMO
First and foremost, do not inject the controller as a dependency. Remember: you are registering it after you create the module, and adding it to that model. Thus, it would make no sense to inject it at the time of creating the module. It doesn't exist yet. Makes sense?
Then some stuff to make life easier for you: separate out your app config stuff from your controller registrations. Have an app.js for example doing the code below. Notice I separated the steps, and I also create a config function that I then call in the app.config. This is just a bit more readable in the JavaScript mess we have to deal with.
(function() {
'use strict';
var app = angular.module('app', ['ngResource']);
var config = function(routeProvider){
routeProvider.when("/", {templateUrl: 'www/index.html', controller: 'mainController'});
};
app.config(['$routerProvider'], config);
})
})();
Then have a mainController.js containing the controller code and the registration of it. It'll be more future-proof for when you start adding more controllers and services and so on. Also, don't use $scope, use 'this' instead, you can use that from version 1.5 I think. Only place when you need to use $scope because 'this' doesn't work there is in angular charts, just a heads up ;)
(function ()
{
'use strict';
var mainController = function ($scope,)
{
var vm = this;
vm.variable = "value";
};
angular.module('app').controller('mainController', ['', mainController]);
})();
Btw don't mind the strange indentation of the code snippets, the editor on this page is messing with me a bit ;)

AngularJS minified js files not working

I minified and merged all js files in one and included in html nothing is working in site.
There are so many files in js and I dont want include all one by one, so modified and merged all in one.
Is there any other way to decrease number of http calls for js files.
When minifying your AngularJS documents it is important that you follow the docs for dependancy injection, otherwise your code can break. You should make sure you are using the preferred array method an example can be seen below:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
As seen in the official Angular JS docs: https://docs.angularjs.org/guide/di.
It seems, that's a reason of implicit dependency injection. According to the Angular JS documentation:
Careful: If you plan to minify your code, your service names will get renamed and break your app.
Use strict dependency injection instead. For example:
angular
.module("MyModule")
.controller("MyCtrl", ["$scope", "$timeout", function ($scope, $timeout) {
...
}]);
More over, consider using ng-annotate that's much easier:
angular
.module("MyModule")
.controller("MyCtrl", function ($scope, $timeout) {
"ngInject";
...
});
To follow up on #dayle-salmon 's answer, if you have your controllers like this
app.controller('DemoCtrl', function(dependency1, dependency2){
// controller code
});
Change it to
app.controller('DemoCtrl', ['dependency1', 'dependency2', function(dependency1, dependency2){
// controller code
}]);
Reason JS minificators usually change the name of the dependency that is injected. And Angular wont have a clue on what the dependency is. So, you manually declare them so it won't cause a problem after minification!

AngularJS Controller is not a function error

I'm getting error when adding ng-controller="HeaderController" to a div.
Error: ng:areq
Bad Argument
Argument 'HeaderController' is not a function, got undefined
my HTML looks like that:
<div ng-app="myApp">
<div ng-controller="HeaderController">
</div>
<div ng-controller="PostController">
</div>
</div>
Also I include following files:
MyApp.js
var myApp = angular.module('myApp', ['postServices', 'angularFileUpload', 'ngSanitize', 'ui.date', 'bootstrapLightbox', 'profileServices']);
HeaderController.js
myApp.controller('HeaderController', ['$scope', 'PostServices', '$http', function($scope, PostServices, $http) {
$scope.getBookmarksCount = function() {
PostServices.getBookmarksCount().then(function(response) {
if (response.data.status == 'success') {
$scope.bookmarksCount = response.data.bookmarksCount;
} else {
$scope.errorMessage = response.data.message;
}
})
};
}]);
PostController.js beggining of this file looks like:
myApp.controller('PostController', ['$scope', 'PostServices', '$http', 'FileUploader', 'Lightbox',function($scope, PostServices, $http, FileUploader, Lightbox) {
PostService.js contains a module named postServices and it contains a service PostServices:
angular.module('postServices', [])
.service('PostServices', ['$http', function($http) {
if I delete ng-controller="HeaderController" everything works fine.
Does anyone knows what could be the problem?
In your module you add the postServices without a capital at the start, while you add it in your headercontroller as PostServices. This might mess with the forming of your headercontroller.
Either one of those could be a typo, but it is very important that you inject the service precisely as it is defined (in your .service or .factory) in the ['PostService', bit. So if the service is called: postService, you should inject it in your controller as: ['postService, function(someNameThatDoesntMatter) if its called PostService, inject it as ['PostService', function(someNameThatDoesntMatter)
As I just shown, how you call it afterwards in the function parameter is up to you.
Update
You could create a module for your controllers to fix this. Make sure to inject your postServices in this module aswell. Then inject the controllers module in your myApp module :-) The benefit of working in a structured way like this, is that you can create a structure of including your JS which you can apply on every project you work on.
I don't know which version of Angular you use , I took 1.4.0 for my plunk example and try just to limit to the code you provide to see if I recreated the error.
I had to deal more with scripts inclusion order. It created error. The right order in order to make it work is
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.4.0/angular.js"></script>
<script src="MyApp.js"></script>
<script src="PostController.js"></script>
<script src="PostService.js"></script>
<script src="HeaderController.js"></script>
http://plnkr.co/edit/NhzQFmI1s9r98uAMZwYg
So Main point was to defined PostService.js before HeaderController
It seems likes
you forget include that HeaderController.js file in index.html.
Make sure your HeaderController.js is loaded properly.
Missing some where in gulp/grunt process.

AngularJS Injector - Error: [$injector:unpr] Unknown provider: $rootScopeProvider <- $rootScope

May be it's trivial question, but for AngularJS newbie it's a matter ^_^
What I'm trying to originally achieve is to make a dynamically inserted tag (by jQuery) with ng-click directive to work. I've searched and found that I've to get AngularJS Injector, then compile that code. So here it is the simplest form of the injector code which is NOT working for me, what's wrong with it?
Note #1: The dynamically inserted tag with ngDirective is done outside AngularJS scope.
angular.module('simpleExample', [])
.run(
[ '$rootScope',
function ($rootScope) {
$rootScope.test = "Test";
}]);
console.log(angular.injector(['simpleExample']));
// console.log(angular.injector(['simpleExample']).$compile('Text'));
http://jsfiddle.net/Zx8hr/6/
The ng module
angular.bootstrap automatically adds the ng module to the dependencies when used (manually or with ngApp)
$rootScope / $compile services are part of the ng module.
You need to use injector.invoke if you want these services.
You should probably use angular in more traditional ways.
Try this:
angular.module('simpleExample', ['ng']);
angular.injector(['simpleExample'])
.invoke(['$rootScope','$compile',
function($rootScope, $compile){
var elm = $compile('Text')($rootScope);
$rootScope.someFunctionOnRootScope = function(){
alert("Hello there!");
}
angular.element(document.body).append(elm);
}]);

Angular JS Uncaught Error: [$injector:modulerr]

I am having a problem with Angular JS receiving an error : Uncaught Error: [$injector:modulerr].
My JS-file looks
angular.module('MyApp', ['ngRoute']);
angular.module('MyApp',['ngResource']);
function TwitterCtrl($scope,$resource){
}
I also included angular-route-js
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js">
Angular documentation says the problem is http://docs.angularjs.org/api/ngRoute
In development environments I recommend you to use not minified distributives. And all errors become more informative! Instead of angular.min.js, use angular.js.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js">
Try adding this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
Try adding:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js">
and:
angular.module('MyApp', ['ngRoute','ngResource']);
function TwitterCtrl($scope,$resource){
}
You should call angular.module only once with all dependencies because with your current code, you're creating a new MyApp module overwriting the previous one.
From angular documentation:
Beware that using angular.module('myModule', []) will create the
module myModule and overwrite any existing module named myModule. Use
angular.module('myModule') to retrieve an existing module.
Make sure you're function is wrapped in a closure, complete with the extra () at the end:
(function(){
var app = angular.module('myApp', []);
})();
I previously had the same issue, but I realized that I didn't include the "app.js" (the main application) inside my main page (index.html).
So even when you include all the dependencies required by AngularJS, you might end up with that error in the console. So always make sure to include the necessary files inside your main page and you shouldn't have that issue.
Hope this helps.
The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
var app = angular.module('myapp', ['ngRoute']);
This is getting reference from: AngularJS 1.2 $injector:modulerr David answer
I had the same problem. You should type your Angular js code outside of any function like this:
$( document ).ready(function() {});
I got this error because I had a dependency on another module that was not loaded.
angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...
so even though I had all the Angular modules, I didn't have the kendo one.
ok if you are getting a Uncaught Error: [$injector:modulerr] and the angular module is in the error that is telling you, you have an duplicate ng-app module.
Make sure that the variable that holds your angular.module is structured correctly.
This will fail with "Uncaught Error: [$injector:modulerr]":
var angApp = angular.module("angApp");
This works:
var angApp = angular.module("angApp", []);
It's a sneaky one since the error message doesn't point to one thing in particular (Thus the wide variety of answers). Additionally, most js linters won't catch the particulars. Keep at it!
I had exactly the same problem and what resolved it was to remove the closure:
$(function(){
var app = angular.module("myApp", []);
app.controller('myController', function(){
...
});
});
becomes:
var app = angular.module("myApp", []);
app.controller('myController', function(){
...
});
The error means that the dependency injector was unable to locate the dependency 'ngResource'. The script tag in the accepted answer provides this dependency.
You will also get the same error if you add any custom modules in the dependencies but did not add the script tag for including the '.js' file containing the dependency.
Just throwing this in in case it helps, I had this issue and the reason for me was because when I bundled my Angular stuff I referenced the main app file as "AngularWebApp" instead of "AngularWebApp.js", hope this helps.
I had also same issue, I have just removed following line of code from BundleConfig.cs file and my code is working fine.
BundleTable.EnableOptimizations = true;
Do not load the javascript inside the cdn link script tag.Use a separate script tag for loading the AngularJs scripts.
I had the same issue but I created a separate <script>
Then the error gone.

Categories