Including Angular configuration Module - javascript

I have trouble building an Angular module that stores all the configuration data and then including it in my main Angular module.
The idea is for the system to be able to change the configuration data. So the main Module code and controller codes are the same but the config module is different.
I have tried many different way to get this to work but they all give me a series of errors.
My config modules looks like this
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
});
My main (condensed) module looks like this. Note I'm using it with a blade template for the brackets.
(function( ){
var app = angular.module('favoriteeats', ['favoriteeats.config','ngResource'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})();
My controller looks like this.
(function( ){
var app = angular.module('favoriteeats');
app.controller('EntrustRolePermissions', function($scope, $controller) {
angular.extend(this, $controller('BaseController', {$scope: $scope}));
var vm = this;
vm.roles = [ ];
vm.user_roles = [ ];
vm.updateRoles = function(){
ret = vm.restApi('role','GET');
console.log(ret);
}
vm.updateRoles( );
}) //end contoller
})();
When I include the config module script in the head I get this error.
"Error: [$injector:modulerr] Failed to instantiate module favoriteeats due to:
[$injector:modulerr] Failed to instantiate module favoriteeats.config due to:
[$injector:nomod] Module 'favoriteeats.config' 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."
When I include the config module script in the footer after lazying loading the JS I get the same error.
If I add the config module script to a separate JS file and add this before or after the main module js file I get the same error.
The only way it seem to work is if I included in the same `(function( ){' container as the main module. IE
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
var app = angular.module('favoriteeats', ['favoriteeats.config','ngResource'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})();
Why is this? How can I extract it and include my config script from another location!?!? I cannot find the answer to determine what is wrong.

You should declare a module by indicating its dependencies (in this case an empty array) and then you have to execute the function:
(function( ){
angular.module('favoriteeats.config', [])
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
})();

You're referencing the 'favoriteeats.config' module instead of defining it. If you add the empty list of dependencies, it should work.
angular.module('favoriteeats.config', [])

You have a faulty IIFE.
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
}); // This does not close the IIFE.
Change it to:
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
}()); // or })();
edit; I didn't even pay attention to the fact that you are not defining your module, but rather referencing it. Like #joao and #mithon suggested - add some brackets:
angular.module('favoriteeats.config', [])

Related

AngularJS Unit Test: Module 'admin.module' is not available

I'm testing an Angular controller using Karma and Jasmine but I can't seem to load in my module from my main class.
Here's my main class: admin.controller.js
angular.module('admin.module').controller('admin.controller', ['$scope', function ($scope) {
$scope.SaveChanges = function()
{
return true;
}
}]);
Here's my test class: admin.controller.tests.js
describe('admin.controller tests', function () {
beforeEach(module('admin.module'));
var $controller = {};
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
describe('$scope.SaveChanges', function () {
it('Should return true', function () {
var $scope = {};
var controller = $controller('admin.controller', { $scope: $scope });
expect($scope.SaveChanges()).toBe(true);
});
});
});
My karma.conf.js file points to the following files in my project:
// list of files / patterns to load in the browser
files: [
'../TriAngular/scripts/angular.js',
'../TriAngular/scripts/angular-mocks.js',
'../TriAngular/app/admin/*.js',
'app/admin/*.js'
],
The admin.controller.js file is inside ../TriAngular/app/admin and my admin.controller.test.js is inside 'app/admin'.
I have tried to directly reference the files in my karma config file which has not worked. The full error is:
Module 'admin.module' 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.
The issue turned out to not be obviously from the exception being shown. I was missing a angular-route.js file which needed to be included as it looked like my admin module was dependent on it.
List of includes in my karma.conf.js file:
// list of files / patterns to load in the browser
files: [
'../TriAngular/scripts/angular.js',
'../TriAngular/scripts/angular-mocks.js',
'../TriAngular/scripts/angular-route.js',
'../TriAngular/app/admin/*.js',
'app/admin/*.js'
],
Try;
beforeEach(function(){
module('admin.module');
}
});
I'm not familiar with Karma, but you also need to register your module as well, I've only ever used Jasmine with resharper so what I do to register files is;
/// <reference path="../scripts/app.js" />
At the top of the file.
Also don't forget to reference your module's dependencies as well.

Multiple services in Ionic - how to structure multiple services in one file?

I have a question about Ionic services. As you know, Ionic framework comes with a built in www directory which contains the js directory, which contains the services.js file. My first service works. I attempted to write another service in the same, services.js file and as it turns out, I got an error: Uncaught "SyntaxError: Unexpected token . http://localhost:8100/js/services.js Line: 57" in addition to "(index):28 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module starter.services due to:
Error: [$injector:nomod] Module 'starter.services' 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." Anyway, here's my code, take a look and let me know what I can do differently. Also, if you need more snippets, let me know!
//services.js
//the first factory, API works
angular.module('starter.services', [])
.factory('API', function($http) {
var apiFooUrl = 'http://localhost:3000/api/do/thing'
return {
all: function(){
return $http.get(apiFooUrl + 's')
},
show: function(thingID){
console.log("stock service get running", thingID);
return $http.get(apiFooUrl + '/' + thingID)
}
};
});
//this is the one that returns the error
.factory('Users', function($http) {
var apiUrl = 'http://localhost:3000/api/users/'
return {
index: function(){
return $http.get(apiUrl)
}
show: function(id){
return $http.get(apiUrl + id)
}
}
})
Edited for more info:
So in response to David L's comment:
I've injected it into my GlobalCtrl like so:
.controller('GlobalCtrl', function(Users, $rootScope, $state, $window,
Things, $scope){
$scope.newUser = {}
$scope.user = {}
//show all Users
Users.index().success(function(results){
$scope.users = results
})
})
It'll also be injected into a DetailCtrl as well.
In app.js, the services are injected like so:
angular.module('starter', ['ionic', 'starter.controllers',
'starter.services'])
There's a lot more that needs to go on eventually so I want to make sure I have it right, now.
Have I included the starter.controllers properly? Do I have to include more than one if I have multiples?
They are indeed included in the index.html file.
you have added service after closing the module,
removing the semicolon will solve this problem
}) //here reomved the semicolon
//this is the one that returns the error
.factory('Users', function($http) {

Angularjs - Dynamic configuration based on Environment

I have a sample angular APP - app.js
angular
.module('myUiApp', [
'restangular',
'ngRoute',
'ngCookies',
'ui.bootstrap',
'ui.sortable',
'smart-table',
'config'
])
.config(function($routeProvider, $httpProvider, $sceProvider, $logProvider, RestangularProvider, config) {
RestangularProvider.setBaseUrl(config.apiBaseUrl);
RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
//routing here
.....
});
my Config.js looks like -
angular.module('config', []).service('config', function($location, ENV) {
return ENV.dev;
});
my constants.js looks like -
'use strict';
angular.module('config', []).constant('ENV', (function() {
return {
dev: {
appBaseUrl:'http://localhost:9000/',
apiBaseUrl:'http://localhost:8082/api/'
}
}
})());
I am getting the error saying, Failed to instantiate module myUiApp due to:
[$injector:unpr] Unknown provider: config.
My assumption is injecting config module will invoke the service, which in turn return the json object. any thoughts or suggesstions to do this dynamic config better?
You can only inject providers into an angular .config() block. You're attempting to inject a service, and that is likely the cause of your error.
Also, you have angular.module('config', []) in two different places. This should only be used once to instantiate the module. Use angular.module('config') (without the second argument) subsequently to reference that module.
I would avoid calling the module config, in favor of something that isn't a method used by angular module.config() -- maybe myConfigModule
Secondly, make sure your script includes the constants.js file and the Config.js file before it includes the app.js file
Lastly double check that this situtation is not affecting you:
defining the module twice with angular.module('config', []) ( emphasis on the [ ] ..) When you define the module with the square brackets, you are saying "New Module". In the second file that you include, change it to angular.module('config') -- or, combine the files into this:
angular.module('myConfigModule', [])
.constant('ENV', (function() {
return {
dev: {
appBaseUrl:'http://localhost:9000/',
apiBaseUrl:'http://localhost:8082/api/'
}
}
}).service('config', function($location, ENV) {
return ENV.dev;
});
UPDATE: And typically I see this syntax for controllers, services, anything that is injecting anything else
.service('config', ['$location', 'ENV', function($location, ENV) {
return ENV.dev;
}]); // see beginning and end of square bracket
// also add new injected modules to both the array (surrounded by quotes) and the function

angular module not available even though it's defined

When I try to run the code below I get two errors that say
Error: [$injector:nomod] Module 'rooms' 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.
Error: [$injector:modulerr] Failed to instantiate
module app due to: [$injector:nomod] Module 'app' 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.
I can see that I haven't misspelled the the name of the module anywhere and I have included the dependencies for the necessary modules and I have structured the modules in the necessary order so that none of the modules are undefined for each other(as in rooms.controllers module exists before it's injected and rooms module exists before it's injected into the app module
(function(){
'use strict';
//create the module that is going to contain the controllers for the rooms module
angular.module('rooms.controllers', [])
.controller('RoomCtrl', RoomCtrl);
function RoomCtrl(){
var vm = this;
vm.rooms = [];
};
})();
(function(){
'use strict';
//create the rooms module and inject rooms.controllers module and ngRoute module
angular
.module('rooms', ['rooms.controllers', 'ngRoute']);
});
(function(){
'use strict';
//get the rooms module and config it's routes, because we're getting it we don't need []
angular
.module('rooms')
.config(function($routeProvider){
$routeProvider
.when('/rooms',{
templateUrl:'public/modules/rooms/templates/roomlist.html',
controller: 'RoomCtrl',
controllerAs: 'room'
})
})
})();
(function(){
'use strict';
//bootstrap the whole thing together
angular.module('app', ['rooms']);
})();
This code block is not executed.
(function(){
'use strict';
//create the rooms module and inject rooms.controllers module and ngRoute module
angular.module('rooms', ['rooms.controllers', 'ngRoute']);
})(); // <-- here

RequireJS + Angular: Undefined app. Callback doesn't shoot

I got main.js with this simple code:
'use strickt';
require.config({
paths: {
'angular' : 'libs/angular' ,
'angular-router' : 'libs/angular-route' ,
},
shim : {
'angular' : {
exports : 'angular'
},
'angular-router' : {
deps: ['angular']
}
}
});
require(['app'], function (mainApp) {
console.log(mainApp);
});
As you can see, I try to fetch app inside require callback. But all I got its undefined.
Here what I got inside app.js file:
define('mainApp', ['angular', 'angular-route'], function (angular) {
var app = angular.module('mainApp', ['ngRoute']);
console.log('should be fired from app.js');
return app;
});
So the question:
Function argument 'mainApp' as undefined inside main.js callback seems logical because console.log() inside app.js doesnt shoot. Can somebody tell me what is wrong with it?
Just remove module name in app.js file (or change it to 'app'). You app.js file will look like:
define(['angular', 'angular-route'], function (angular) {
var app = angular.module('mainApp', ['ngRoute']);
console.log('should be fired from app.js');
return app;
});
http://requirejs.org/docs/api.html#modulename
You can explicitly name modules yourself, but it makes the modules
less portable -- if you move the file to another directory you will
need to change the name. It is normally best to avoid coding in a name
for the module and just let the optimization tool burn in the module
names. The optimization tool needs to add the names so that more than
one module can be bundled in a file, to allow for faster loading in
the browser.

Categories

Resources