Angular Module Config block is never getting called - javascript

Angular Config module is not getting invoked.
In the below code snippet, app.state.js is getting invoked, but the config part it's not. Please help me out on this.
This is used in a jhipster application
**app.module.js :**
(function() {
'use strict';
var app= angular
.module('IloadsApp', [
'ngStorage',
'tmh.dynamicLocale',
'pascalprecht.translate',
'ngResource',
'ngCookies',
'ngAria',
'ngCacheBuster',
'ngFileUpload',
'ui.bootstrap',
'ui.bootstrap.datetimepicker',
'ui.router',
'infinite-scroll',
// jhipster-needle-angularjs-add-module JHipster will add new module here
'angular-loading-bar'
]);
app.run(run);
run.$inject = ['stateHandler', 'translationHandler'];
function run(stateHandler, translationHandler) {
stateHandler.initialize();
translationHandler.initialize();
}
})();
**app.state.js :**
(function() {
'use strict';
angular
.module('IloadsApp')
.config(stateConfig);
stateConfig.$inject = ['$statePsrovider'];
alert ("before Inside ");
function stateConfig($stateProvider) {
alert ("Inside ");
$stateProvider.state('app', {
abstract: true,
views: {
'navbar#': {
templateUrl: 'app/navbar/navbar.html',
controller: 'NavbarController',
controllerAs: 'vm'
}
},
resolve: {
authorize: ['Auth',
function (Auth) {
return Auth.authorize();
}
],
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('global');
}]
}
});
}
alert("After");
})();

Related

angular.js:10126 Error: [ng:areq] Argument […] is not a function, got undefined

I know it's duplicate but mine doesn't work .I searched a lot.
Angular routing to some pages which I want to load their controller using requirejs fails
app.js
define("app", ['angular', 'angularUiBootstrap'], function () {
var app = angular.module('app', ['ngCookies', 'ngRoute']);
app.config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
}]);
return app;
});
routing.js
define('routing', ['app', 'safeApply'], function (app) {
app.factory('api', function ($http, $cookies) {
return {
init: function (token) {
debugger;
$http.defaults.headers.common['X-Access-Token'] = token || $cookies.token;
}
};
});
/////////////////////////////
app.factory('httpInterceptor', function httpInterceptor($q, $window, $location) {
return function (promise) {
var success = function (response) {
return response;
};
var error = function (response) {
if (response.status === 401) {
$location.url('/login');
}
return $q.reject(response);
};
return promise.then(success, error);
};
});
/////////////////////////
app.config(function ($routeProvider, $locationProvider, $httpProvider, $provide) {
var routingCfg =
[
{ path: '/', controller: 'MainPageController', isFree: true, category: 'User', actionUrl: '/Home/MainPage' },
{ path: '/UploadNationalCard2', controller: 'UploadNationalCardController2', isFree: true, category: 'User', actionUrl: '/UploadNationalCard/Index' },
{ path: '/SmsReply', controller: 'SmsReplyJsController', isFree: true, category: 'User', actionUrl: '/SmsReply/Index' },
{ path: '/Support', controller: 'SupportController', isFree: true, category: 'User', actionUrl: '/Support/Index' },
{ path: '/Rule', controller: 'RuleController', isFree: true, category: 'User', actionUrl: '/Rule/Index' },
{ path: '/Api', controller: 'ApiController', isFree: true, category: 'User', actionUrl: '/Api/Index' },
{ path: '/Language', controller: 'LanguageController', isFree: true, category: 'User', actionUrl: '/Language/Index' },
{ path: '/About', controller: 'AboutController', isFree: true, category: 'User', actionUrl: '/About/Index' },
];
routingCfg.forEach(function (x) {
$routeProvider.when(x.path, {
templateUrl: x.actionUrl,
controller: x.controller,
resolve: {
load: ['$q', '$rootScope', 'safeApply', '$location', function ($q, $rootScope, safeApply, $location) {
var deferred = $q.defer();
require([x.controller], function () {
safeApply($rootScope, function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
});
return app;
});
requirejsConfig.js
/// <reference path="routing.js" />
require.config({
baseUrl: '/',
urlArgs: 'v=1.0',
skipDataMain: true,
paths: {
bootstrap: 'Scripts/bootstrap.min',
jquery: 'Scripts/jquery-1.10.2.min',
angular: 'Scripts/angular-1.4.7/angular',
angularRoute: 'Scripts/angular-1.4.7/angular-route',
angularCookies: 'Scripts/angular-1.4.7/angular-cookies',
angularUiBootstrap: 'app/lib/ui-bootstrap/ui-bootstrap-tpls-0.10.0.min',
app: 'app/js/app',
routing: 'app/js/routing',
safeApply: 'app/js/safeApply',
serviceBaseAngular: 'app/js/serviceBaseAngular',
UserPageController: 'app/user/UserPageController',
MainPageController: 'app/user/MainPageController',
UploadNationalCardController2: 'app/user/UploadNationalCardController2',
SmsReplyJsController: 'app/user/SmsReplyJsController',
},
shim: {
'bootstrap': ["jquery"],
'angularUiBootstrap': ['angular'],
'app': ['angular', 'angularRoute'],
'angular': {
deps: ["jquery"],
exports: 'angular'
},
'angularRoute': ['angular'],
'angularCookies': ['angular'],
},
});
require(
[
'app',
'routing',
'jquery',
'bootstrap',
'angular',
'angularUiBootstrap',
'safeApply',
'angularCookies',
'angularRoute',
'serviceBaseAngular',
'UserPageController',
'MainPageController',
'UploadNationalCardController2'
],
function (app) {
//app.init();
angular.bootstrap(document, ['app']);
});
this works because it is in the require part of reuirejsConfig.js
MainPageController.js
define("MainPageController", ['app'], function (app) {
app.controller('MainPageController', ["$scope", "serviceBaseAngular",
"$compile", "$timeout", "$location", "$rootScope", function ($scope,
serviceBaseAngular, $compile, $timeout, $location, $rootScope) {
}]);
});
MainPage.cshtml
<div ng-controller="MainPageController">
</div>
but SmsReplyJsController.js doesn't work
define('SmsReplyJsController', ['app'], function (app) {
app.controller('SmsReplyJsController', ["$scope", "$location", "$routeParams", "sharedServices", function ($scope, $location, $routeParams, sharedServices) {
}]);
});
and I get this error
VM976:27 Error: [ng:areq] Argument 'SmsReplyJsController' is not a function,
got undefined
http://errors.angularjs.org/1.4.7/ng/areq?
p0=SmsReplyJsController&p1=not%20aNaNunction%2C%20got%20undefined
which means
Error: ng:areq
Bad Argument
Argument 'SmsReplyJsController' is not a
Description
AngularJS often asserts that certain values will be present and truthy using a helper function. If the assertion fails, this error is thrown. To fix this problem, make sure that the value the assertion expects is defined and matches the type mentioned in the error.
If the type is undefined, make sure any newly added controllers/directives/services are properly defined and included in the script(s) loaded by your page.
error-ngareq-from-angular-controller didn't help me
Any help! thanks
The line that causes error is in safeApply.js
define("safeApply", ['app'], function (app) {
console.log('safeApply')
app.factory('safeApply', [function () {
return function ($scope, fn) {
var phase = $scope.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && typeof fn === 'function') {
$scope.$eval(fn);
}
} else {
if (fn && typeof fn === 'function') {
$scope.$apply(fn);
} else {
$scope.$apply();
}
}
};
}]);
});
it is
if (fn && typeof fn === 'function') {
$scope.$apply(fn);
}
actually after angular routing, which uses safeApply to load dependencies first then the controller, when it loads the controller using "$scope.$apply(fn);" the error occurs
$routeProvider.when(x.path, {
templateUrl: x.actionUrl,
controller: x.controller,
resolve: {
load: ['$q', '$rootScope', 'safeApply', '$location', function ($q, $rootScope, safeApply, $location) {
var deferred = $q.defer();
require([x.controller], function () {
safeApply($rootScope, function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
});
Can you give me some hint to solve it!
Solved
I added lazy to my app
define("app", ['angular', 'angularUiBootstrap'], function () {
var app = angular.module('app', ['ui.bootstrap', 'ngRoute', 'ngCookies','ngAnimate']);
app.config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide', function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
}]);
return app;
});
and controllers like
define("NewContactController", ['app'], function (app) {
app.lazy.controller('NewContactController', ["$scope", "serviceBaseAngular", "sharedServices", "$compile", "$timeout", "$location", "$rootScope", "$routeParams", function ($scope, serviceBaseAngular, sharedServices, $compile, $timeout, $location, $rootScope, $routeParams) {
}]);
});

Angularjs load module based on conditions

i am using angularjs and gulp for my application.
here is my directory structure.
content of app.js is
'use strict';
angular.module('BlurAdmin', [
'ngAnimate',
'ui.bootstrap',
'ui.sortable',
'ui.router',
'ngTouch',
'ngRoute',
'ngStorage',
'MyApp.theme',
'MyApp.pages'
]).run(function ($rootScope, $sessionStorage) {
$rootScope.sessionStorage = $sessionStorage;
});
it load page.module.js
content of the page.module.js is
(function () {
'use strict';
var myApp = angular.module('MyApp.pages', [
'ui.router',
])
.config(routeConfig);
/** #ngInject */
function routeConfig($urlRouterProvider, baSidebarServiceProvider) {
$urlRouterProvider.otherwise('/dashboard');
}
var lazyModules = [
'MyApp.pages.dashboard',
'MyApp.pages.create',
'MyApp.pages.otherModule'
];
angular.forEach(lazyModules, function (dependency) {
myApp.requires.push(dependency);
});
})();
This will load all module as menu item in my page. i want to make it conditional based on type of loggedin users.
for that i have used $sessionStorage in .run of app.js, but i am not able to use it in pages.module.js
please help me to load module conditional for example if role is admin then only create module sould be loaded etc..
Thanks.
If i understand correctly you need require.js
Check role and go to page something like "/admin".
$routeProvider.when("/admin", angularAMD.route({
templateUrl: 'your.html', controller: 'createController',
controllerUrl: 'create'
})).when("/other", angularAMD.route({
templateUrl: 'your.html', controller: 'otherController',
controllerUrl: 'other'
}))
https://www.codeproject.com/Articles/808213/Developing-a-Large-Scale-Application-with-a-Single
Try someting like this:
(function () {
'use strict';
var myApp = angular.module('MyApp.pages', [
'ui.router',
])
.config(routeConfig)
.run(lazyModules);
/** #ngInject */
function routeConfig($urlRouterProvider, baSidebarServiceProvider) {
$urlRouterProvider.otherwise('/dashboard');
}
function lazyModules($sessionStorage) {
var userModules = [
'MyApp.pages.dashboard',
'MyApp.pages.otherModule'
];
var adminModules = [
'MyApp.pages.create',
'MyApp.pages.otherModule'
];
var isAdmin = $sessionStorage.admin;
var loadModules = isAdmin ? adminModules : adminModules;
angular.forEach(loadModules, function (dependency) {
myApp.requires.push(dependency);
});
}
})();

AngularJS Service Undefined When Injected

Stackoverflow has numerous questions under this title but I'm going through each one and not seeing what I'm doing meaningfully differently. More to the point, this isn't my only service, and the rest of them work.
My service:
(function () {
var envService = function ($location) {
//Removed
return {
//Removed for SO, was simply an object of functions
}
var module = angular.module('passwordResetApp');
module.factory('envService', ['$location', envService]);
}());
My app.js:
(function () {
'use strict';
var app = angular.module('passwordResetApp', ['ngRoute', 'AdalAngular', 'ui.grid', 'ui.grid.pagination', 'ui.grid.edit', 'ui.grid.cellNav', 'ui.grid.selection']);
app
.config([
'$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', '$locationProvider',
function ($routeProvider, $httpProvider, adalProvider, $locationProvider) {
$routeProvider
.when('/home',
{
templateUrl: '/app/views/home.html',
caseInsensitiveMatch: true
})
.when('/PasswordReset',
{
templateUrl: '/app/views/passwordReset.html',
controller: 'ResetRequestController as vm',
//requireAdLogin: true,
caseInsensitiveMatch: true
})
.when('/UserSearch',
{
templateUrl: '/app/views/userSearch.html',
controller: 'UserSearchController as vm',
//requireAdLogin: true,
caseInsensitiveMatch: true
})
.otherwise({ redirectTo: '/home' });
adalProvider.init(
{
instance: 'https://login.microsoftonline.com/',
tenant: 'Removed for SO',
clientId: 'Removed for SO',
requireADLogin: false,
//anonymousEndpoints: [
// '/'
//],
//endpoints: [
// '/'
//],
extraQueryParameter: 'nux=1',
cacheLocation: 'localStorage',
// enable this for IE, as sessionStorage does not work for localhost.
},
$httpProvider
);
$locationProvider.html5Mode(true).hashPrefix('!');
}
]
);
app.directive('header',
function() {
return {
//Attribute, not element
restrict: 'A',
replace: true,
templateUrl: 'app/views/_header.html',
controller: 'HeaderController as vm',
caseInsensitiveMatch: true
}
});
app.directive('footer',
function() {
return {
restrict: 'A',
replace: true,
templateUrl: 'app/views/_footer.html',
caseInsensitiveMatch: true
}
});
app.run([
'$route', '$http', '$rootScope', '$location',
function ($route, $http, $rootScope) {
$http.defaults.withCredentials = true;
$rootScope.getUrlPath = function (url) {
return baseUrl + url;
};
}
]);
}());
And the controller attempting to have the service injected:
(function () {
'use strict';
var app = angular.module('passwordResetApp');
var headerController = function ($scope, $location, envService, adalService) {
var vm = this;
vm.currentUser = {};
vm.environment = envService.getEnvironment();
vm.changeView = function(view) {
$location.path(view);
};
vm.login = function () {
adalService.login();
};
vm.logout = function () {
adalService.logOut();
};
};
app.controller('HeaderController', ['adalAuthenticationService', headerController]);
}());
You have to inject all the dependencies in DI array, in order to use them in controller function. Make sure the sequence should not get messed up.
app.controller('HeaderController', ['$scope', '$location', 'envService', 'adalService', headerController]);

AngularJS unknown provider: $routeProviderProvider

I'm struggling with this unknown provider error and just wondering what I'm doing wrong. Have this structure:
in main.js
'use strict';
angular.module('myApp')
.controller('MainCtrl', ['navService', function (navService) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
this.active = false;
navService.getPosition();
}]);
In index html I have ng-controller="MainCtrl"
And finally in navService:
angular.module('myApp')
.factory('navService', ['$routeProvider', '$location', function ($routeProvider, $location) {
function getPosition() {
/*code here */
}
return {
getPosition: getPosition
};
}]);
In main app.js
angular
.module('cavyrApp', [
'ngAnimate',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
]).config...........
$routeProvider is a provider - you can not inject it into factory/service. You can inject it to the config method only - to configure the service it will provide:
module.config(function($routeProvider) {
// configure the routes here
});
You should inject your factroy like this:
angular.module('myApp',['ngRoute']); //route inject
and the controller:
angular.module('myApp').controller('MainCtrl', function(navService) {
});

safari error angular controller not a function

I have a error where Safari is trowing error that my controllers are not a function
Error: [ng:areq] Argument 'TranslateController' is not a function, got undefined
My router calling controller here ->
(function() {
'use strict';
angular
.module('welcome.module')
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('welcome', {
url: '/welcome',
views: {
'header': {
templateUrl: 'app/welcome/header.html',
controller: 'TranslateController'
},
'sidebar': {},
'content': {
templateUrl: 'app/welcome/welcome.html',
controller: 'WelcomeController'
},
'footer': {
templateUrl: 'app/welcome/footer.html',
controller: 'WelcomeFooterController'
}
}
})
}]);
})();
My controller ->
(function() {
'use strict';
angular
.module('welcome.module')
.controller('TranslateController', TranslateCtrl);
TranslateCtrl.$inject = ['$translate', '$scope'];
function TranslateCtrl($translate, $scope) {
'ngInject';
const self = this;
$scope.headerFix = true;
activate();
function activate() {
translate();
}
function translate() {
$scope.changeLanguage = function(langKey) {
$translate.use(langKey);
};
}
}
})();
I have definition of the module of course:
(function() {
'use strict';
angular
.module('welcome.module', [
'ui.router'
]);
})();
I defined controllers and modules and everything in my html.
Everything is working smooth on mozila and chrome but not on Safari :(
Do you have any idea how to solve this issue ?
angular.module('welcome.module')
.controller('TranslateController', ['$scope', '$translate',
function($scope, $translate) {
$scope.headerFix = true;
activate();
function activate() {
translate();
}
function translate() {
$scope.changeLanguage = function(langKey) {
$translate.use(langKey);
};
}
}
]);
Fixed it

Categories