A module fails to load - angularjs

AngularJS v1.6.0.
How to understand what module fails to load? Why and how to fix it?
I get the following error:
angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.0/$injector/modulerr?p0=fooApp&p1=Error%…c%20(http%3A%2F%2Fviic.com%2Flibs%2Fangular%2Fangular.min.js%3A21%3A332)(…)(anonymous function) # angular.js:38(anonymous function) # angular.js:4756q # angular.js:357g # angular.js:4717eb # angular.js:4639c # angular.js:1838Lc # angular.js:1859oe # angular.js:1744(anonymous function) # angular.js:32890b # angular.js:3314
www-embed-player.js:218 GET https://googleads.g.doubleclick.net/pagead/id net::ERR_BLOCKED_BY_CLIENTRd # www-embed-player.js:218Vd # www-embed-player.js:222(anonymous function) # www-embed-player.js:249L # www-embed-player.js:173re # www-embed-player.js:246xk # www-embed-player.js:654(anonymous function) # www-embed-player.js:705(anonymous function) # S0Q4gqBUs7c?controls=0&showinfo=0&enablejsapi=1&showsearch=0&rel=0:10
My app frontend structure:
- public
- js/controllers/VideoChannelCtrl.js
- js/services/CoubService.js
- js/app.js
- js/appRoutes.js
- index.html
- views/player.html
- libs/angular/angular.min.js
- libs/angular-route/angular-route.min.js
...
index.html
...
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/VideoChannelCtrl.js"></script>
<script src="js/services/CoubService.js"></script>
<script src="js/appRoutes.js"></script>
...
js/app.js
var fooApp = angular.module('fooApp', ['ngRoute', 'appRoutes', 'VideoChannelCtrl', 'CoubService']);
js/appRoutes.js
angular.module('appRoutes', [])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
// home page
.when('/', {
templateUrl: 'views/player.html',
controller: 'VideoChannelController'
});
$locationProvider.html5Mode(true);
}]);
js/controllers/VideoChannelCtrl.js
fooApp.controller('VideoChannelController', ['$scope', 'Coub', function($scope, Coub) {
$scope.tagline = 'To the moon and back!';
Coub.get().success(function(data) {
$scope.videolink = data[0].url;
});
}]);
js/services/CoubService.js
angular.module('CoubService', []).factory('Coub', ['$http', function($http) {
return {
get : function() {
return $http.get('/api/videolinks');
},
delete : function(id) {
return $http.delete('/api/videolinks/' + id);
};
}]);

You didn't inject the VideoChannelController controller correctly.
I suggest you to declare your controller like this :
js/controllers/VideoChannelCtrl.js
angular.module('fooApp')
.controller('VideoChannelController', VideoChannelController);
VideoChannelController.$inject = ['$scope', 'Coub'];
function VideoChannelController($scope, Coub) {
$scope.tagline = 'To the moon and back!';
Coub.get().success(function(data) {
$scope.videolink = data[0].url;
});
}
As VideoChannelController controller is declared as controller of fooApp module application, you don't need injection like :
var fooApp = angular.module('fooApp', ['ngRoute', 'appRoutes', 'VideoChannelCtrl', 'CoubService']);
You can remove VideoChannelController from this declaration.
Also, you should refer to the following AngularJS development guideline :
Angular Style Guide

Is VideoChannelCtrl a controller or a module? If it's a controller, then you can't inject it as a module dependency. Remove it from module dependencies - angular.module('fooApp', ['ngRoute', 'appRoutes', 'CoubService']);
Or create separate module and have this controller inside that module and inject the newly created module. Check whether it is really required to have multiple modules in your app. From what I assume from the given code, you don't need multiple modules.
For eg, you can have the service in the same fooApp like this:
angular.module('fooApp').factory('Coub', ....);
angular.module('fooApp') -> gets the already registered module named fooApp and you can add controllers/services/directives etc to the same module.
So, if you add your given controller, service and config to the fooApp module, then you can define the module as
angular.module('fooApp', ['ngRoute']);

Related

Unable to access an angularjs module inside another module

I have an angularJS app with three modules: myApp(parent/core module), services(contains all the factories and services), and controllers(contains all the controllers).
This is my app.js file
angular.module('services', []);
angular.module('controllers', []);
var app = angular.module('myApp', ['services', 'controllers']);
I read here that setting up my modules and defining dependencies in this way will allow each of my modules to access the other without having to inject the dependencies.
Here's my index.html file
<script src="/js/app.js"></script>
<script src="/js/services/testFactory.js"></script>
<script src="/js/controllers/testCtrl.js"></script>
testFactory.js file
angular.module('services').factory('testFactory', ['$rootScope', 'apiCall', function($rootScope, apiCall){
let testFactory = {};
testFactory.testFunc = function(){
console.log('testFactory.testFunc called');
}
return testFactory;
}])
testCtrl.js file
angular.module('controllers').controller('testCtrl', ['$scope', 'testFactory', function($scope, testFactory){
console.log("inside testCtrl");
$scope.testing = function(){
console.log("testing function called");
testFactory.testFunc();
}
}])
When I call the testFactory.testFunc inside the myApp module, it functions correctly. But, when I try calling it in the controller module, I'm getting the following error
TypeError: Cannot read property 'testFunc' of undefined
I even tried injecting the service module inside the controller module as a dependency, but I still got the same error.
How do I get the service module to work inside the controller module?

Angular Error: adding dependecy gives $injector:unpr Unknown Provider

I decided to add ngInfinitiScroll plugin to my application. Hence i called the file :
<script type="text/javascript" src="{!! asset('/js/ng-infinite-scroll.min.js') !!}"></script>
In my events.js file i initiated the module like this:
(function(window) {
// Define the `app` module
var app = angular.module('stayhyper', ['infinite-scroll']);
app.controller('eventController', ['$scope', '$rootScope', '$http', 'myService',
function($scope, $rootScope, $http, myService) {
} // end of main function
]); // end of controller
})(window);
Then I get the following error:
Error: $injector:unpr Unknown Provider
Unknown provider: myServiceProvider <- myService<- eventController
MyService (this is in a seperate js file which is loaded in the header):
app.service('myService', function() {
this.URL= function() {
// set the main route of the site
var subhost = "/"
if (window.location.host == "localhost") {
subhost = "/myapp/public/"
}
window.urlRoot = window.location.origin + subhost;//main root of the site
return window.urlRoot;
}
this.APIURL= function() {
// set the main route of the site
var subhost = "/api/"
if (window.location.host == "localhost") {
subhost = "/myapp/public/api/"
}
window.urlRoot = window.location.origin + subhost;//main root of the site
return window.urlRoot;
}
});
You need to load the event.js initially and then mainapp.js , then only the module will be created initially, also make sure you have added the references in html for infinite-scroll
So the order will be,
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ngInfiniteScroll/1.2.2/ng-infinite-scroll.js"></script>
<script type="text/javascript" src="mainapp.js"></script>
<script type="text/javascript" src="event.js"></script>
also make sure you are not calling the module again.

Unable to load provider

I am trying to use an angular provider so I can dynamically load sub-modules within the $routeProvider of my angular application. However, I am getting one of 2 errors:
Error: [$injector:modulerr] Failed to instantiate module MainApp due to:
[$injector:unpr] Unknown provider: MyRouteProvider
Error: [$injector:nomod] Module 'MainApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Here's what I have:
main.js
require.config({
baseUrl : '',
version : '1.0',
});
require([
'app',
'my-route-mod/my-route-mod.module',
'my-route-mod/my-route-mod.provider',
'main-app/main-app.config',
'main-app/main-app.run',
/* other initial modules */
],function(){
angular.bootstrap(document,['MainApp']);
});
app.js
(function(){
'use strict';
/* global angular, $ */
angular.module('MainApp',[
'MyRouteMod', /* This module does not want to load */
'ngRoute',
'ngCookies'
]);
})();
my-route-mod/my-route-mod.module.js
(function(){
'use strict';
/* global angular */
angular.module('MyRouteMod',[]);
})();
my-route-mod/my-route-mod.provider.js
(function(){
'use strict';
/* global angular */
angular.module('MyRouteMod')
.provider('MyRouteModProvider',Provider);
Provider.$inject = [];
function Provider() {
var provider = this;
provider.$get = function () {
return { route : someFunction };
}
function someFunction(){...}
}
})();
main-app/main-app.config.js
(function(){
/* global angular */
'use strict';
angular.module('MainApp').config(Config);
Config.$inject = [
'MyRouteModProvider',
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide'
];
function Config(
MyRouteModProvider,
$routeProvider,
$locationProvider,
$controllerProvider,
$compileProvider,
$filterProvider,
$provide
) {
/* ... do some config stuff ... */
}
})();
index.html
<!DOCTYPE>
<html>
<head><title>My App</title></head>
<body>
<!-- Some other stuff -->
<div ng-view></div>
<!-- Some other stuff -->
<script src="vendor-stuff"></script>
<script src="vendor/require.js" data-main="main">/script>
</body>
</html>
I took requirejs out of the equation and was getting the same issue with the provider not loading.
I either get that MainApp is not available, or that MyRouteMod is not available, or that MyRouteModProvider is not available.
Suggestions please.
Angular naming conventions. For providers, the string 'Provider' gets added to your constructor name. So, if you have:
angular.module('MyMod').provider('MickeyMouse',Provider);
Then angular will look for 'MickeyMouseProvider'. So, if you do
angular.module('MyMod').provider('MickeyMouseProvider',Provider);
then angular will look for 'MickeyMouseProviderProvider'
Hope this saves you a bit of time.

Constant not injected to config()

I'm trying to modularize my first angular project. Need to make my module views relative to this module. In example below i have sample main module, that require controllers module. I can inject VIEWS_PATH to controller, but no to config(). As i know constant can be injected into config(). What is wrong with that ?
mainModule.js
angular.module('mainModule', ['app.main.controllers'])
.constant('VIEWS_PATH', 'js/modules/main/views');
controllersMain.js
angular.module('app.main.controllers', [])
.config(function($routeProvider, VIEWS_PATH) { // error
$routeProvider.when('/hello', {
templateUrl: VIEWS_PATH+'/hello.html',
controller: 'HelloController'
})
})
.controller('HelloController', function($scope, VIEWS_PATH) {
$scope.hello = 'Hello World!';
console.log('VIEWS_PATH: '+VIEWS_PATH); // ok
});
It's because you defined your VIEWS_PATH constant in one module -mainModule and you're trying to use it in a different module - app.main.controllers.
You can define that constant in app.main.controllers module if you wish to use it in the configuration of that module.
angular.module('app.main.controllers', [])
.constant('VIEWS_PATH', 'js/modules/main/views')
.config(function($routeProvider, VIEWS_PATH) {
$routeProvider.when('/hello', {
templateUrl: VIEWS_PATH+'/hello.html',
controller: 'HelloController'
});
});
But Constants from app.main.controllers module will work in mainModule as it listed as dependency in mainModule like below.
angular.module('mainModule', ['app.main.controllers']);
For example, let's say we defined two modules - MyApp & SomeModule
var someModule = angular.module('SomeModule',['someOtherModule']);
someModule.constant('SOME_CONSTANT','SomeValue');
var myApp = angular.module('MyApp',['SomeModule']);
myApp.constant('TEST_CONSTANT','Test');
myApp.config(function(SOME_CONSTANT){
console.log("from dependent module "+SOME_CONSTANT);
});
With the above setup, SOME_CONSTANT from SomeModule can be used in MyApp but TEST_CONSTANT from MyApp cannot be used in SomeModule.
Here's a sample Pen in action.

Using JSON as a service in AngularJS

I realise there are a few answers to this question on here, but I just can't seem to get them working with my set up. This is a Plunker of what I am trying achieve (not my own work): http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview
Currently, I have this for my index.html file:
<body ng-app="HomeCourtArenaApp">
<div class="container" ng-view></div>
<script src="components/angular/angular.js"></script>
<script src="components/require/require.js"></script>
<script src="components/angular/angular-resource.js"></script>
<script src="scripts/services/data.js"></script>
<script src="scripts/app.js"></script>
</body>
To register the components, I have defined them in the karma.conf.js file:
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular/angular.js',
'app/components/angular/angular-resource.js',
'app/components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
];
To then create the service, I use the same technique that seems to be documented online in most examples:
'use strict';
angular.module('jsonData', ['ngResource'])
.factory('jsonData', function($resource) {
return $resource('data/shoe3Dconfig.js');
});
Where an error seems to be triggered is when I try to define the service in my 'app' variable, where adding the service name stops the content loading ['jsonData']:
'use strict';
var app = angular.module('HomeCourtArenaApp', ['jsonData']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
I would share my views and controllers also, but before I can even use the JSON data in my template, there are an unearthly amount of errors to deal with:
Uncaught Error: Module name "path" has not been loaded yet for context: _. Use require([])
Uncaught Error: Mismatched anonymous define() module: function () {
return getStyleProperty;
}
Uncaught Error: No module: ngResource
There are some other errors also, but these seem to be mainly because the scripts further up the DOM are stopping them loading correctly. Any help would be great!
you could try this :
the app.js:
angular.module('HomeCourtArenaApp', ['HomeCourtArenaApp.services', 'HomeCourtArenaApp.controllers']).
config(['$routeProvider', ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' });
$routeProvider.otherwise({ redirectTo: '/'});
}]);
angular.module('HomeCourtArenaApp.services', ['ngResource']).
factory('JsonData', function($resource){
return $resource('data/shoe3Dconfig.js');
});
angular.module('HomeCourtArenaApp.controllers', []).
controller('MainCtrl', ['$scope', 'JsonData', function($scope, JsonData) {
$scope.objs = JsonData.query();
console.log(objs);
}
}]);
and this is not necessary to load the datas in the html
<script src="scripts/services/data.js"></script>
This edited plunker http://plnkr.co/edit/33qW5VRnQVrHWFlp16kz?p=preview should get you further along the way.
You need to specify the module (jsonData) that you want in your app as a dependency. There is currently no name displayed since your data does not have a name property.
Your JSON service module definition named as 'jsonData'
angular.module('jsonData', ['ngResource'])
This module defines a service provider (factory) 'jsonService'
.factory('jsonService', function($resource) {
You list the 'jsonData' module as a dependency for your module so that you can access anything defined in there
var app = angular.module('plunker', ['jsonData']);
You then use Angular's Dependency Injection to request an instance of jsonService
app.controller('MainCtrl', function($scope, jsonService) {
Note that if you "production-ise" this and minify your JS, you will need to configure the DI code. I will leave that to you to find in the Angular docs.
Does this explain things a bit more?
And you can get the console in plunker by opening the developer tools in your browser.

Resources