safari error angular controller not a function - javascript

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

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) {
}]);
});

Angular Module Config block is never getting called

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");
})();

Error: [$injector:unpr] Unknown provider:

File structure:
app.js
(function () {
"use strict";
var app = angular.module("app", ["common.services", "ngRoute", "ngResource"])
app.config(function ($routeProvider) {
$routeProvider
// route for the home page
//.when('/', {
// controller: 'mainController',
// templateUrl: 'app/linkPages/home.html'
//})
// route for the about page
//.when('/about', {
// controller: 'aboutController',
// templateUrl: 'app/linkPages/about.html'
//})
// route for the contact page
//.when('/contact', {
// controller: 'contactController',
// templateUrl: 'app/linkPages/contact.html'
//})
.when('/', {
controller: 'AgencyListCtrl',
templateUrl: 'app/agencies/agencyListView.html'
})
//.when('/agencyEditView', {
// controller: 'AgencyEditCtrl',
// templateUrl: 'app/agencies/agencyEditView.html'
//});
});
// create the controller and inject Angular's $scope
app.controller('mainController', function ($scope) {
// create a message to display in our view
$scope.message = 'This is the Main controller page';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'This is the about controller page';
});
app.controller('contactController', function ($scope) {
$scope.message = 'This is the contact controller page';
});
}());
common.services.js
(function () {
"use strict";
angular
.module("common.services",
["ngResource"])//common.services
.constant("appSettings",
{
serverPath: "http://localhost:53403/" // will replace production server url
});
}());
agencyResource.js
(function () {
"use strict";
angular.module("app")//common.services
.factory("agencyResource"
["ngResource", "$resource",
"appSettings",
agencyResource])
function agencyResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/v1/agencies/:id", null,
{
'update': { method: 'PUT' },
});
}
}());
agencyListCtrl.js
(function () {
"use strict";
angular
.module("app")
.controller("AgencyListCtrl",
["agencyResource",
AgencyListCtrl]);
function AgencyListCtrl(agencyResource) {
var vm = this;
//agencyResource.query({ $filter: "contains(Abbr,'IOT')" },
// function (data) {
// vm.agencies = data;
// console.log(result);
//})
agencyResource.query({},
function (data) {
vm.agencies = data;
console.log(result);
})
}
}());
ERROR:
HTML1300: Navigation occurred. index.html Error: [$injector:unpr]
Unknown provider: agencyResourceProvider <- agencyResource <-
AgencyListCtrl
http://errors.angularjs.org/1.5.9/$injector/unpr?p0=agencyResourceProvider%20%3C-%20agencyResource%20%3C-%20AgencyListCtrl
at Anonymous function (http://localhost:61924/Scripts/angular.js:4554:13)
at getService (http://localhost:61924/Scripts/angular.js:4707:11)
at Anonymous function (http://localhost:61924/Scripts/angular.js:4559:13)
at getService (http://localhost:61924/Scripts/angular.js:4707:11)
at injectionArgs (http://localhost:61924/Scripts/angular.js:4731:9)
at instantiate (http://localhost:61924/Scripts/angular.js:4774:7)
at $controller (http://localhost:61924/Scripts/angular.js:10533:7)
at link (http://localhost:61924/Scripts/angular-route.js:1056:9)
at Anonymous function (http://localhost:61924/Scripts/angular.js:1258:11)
at invokeLinkFn (http://localhost:61924/Scripts/angular.js:10095:9)
I am not sure weather I have injected everything right here? Any help would be appreciated. This is my first angular app so I am a little green. Stack Overflow is telling me I have to type more details but the code post are pretty self explanatory. I
The answer is that I was declaring ngResource in the agencyResource.js file. It should look like this. MY BAD.
agencyResource.js
(function () {
"use strict";
angular.module("common.services")//common.services
.factory("agencyResource",
[
"$resource",
"appSettings",
agencyResource
])
function agencyResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/v1/agencies/:id", null,
{
'update': { method: 'PUT' },
});
}
}());

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]);

error on dependency injection in interceptor

I have three files app.js, common.services.js and tokenContainer.js . When i tried to inject tokenContainer dependency to interceptor of app.js, I get an error :
Uncaught Error: [$injector:unpr] Unknown provider: tokenContainerProvider <- tokenContainer <- $http <- $templateRequest <- $compile
common.service.js file
(function () {
"use strict";
angular
.module("common.services",
["ngResource"])
.constant("appSettings",
{
serverPath: "http://localhost:6359"
});
}());
tokenContainer.js file :
(function () {
"use strict";
angular
.module("common.services")
.factory("tokenContainer",
[tokenContainer])
function tokenContainer() {
var container = {
token: ""
};
var setToken = function (token) {
container.token = token;
};
var getToken = function () {
};
return {
getToken: getToken
};
};
})();
app.js file :
(function () {
var app = angular.module("productManagement",
["ngRoute", "common.services"]);
app.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when("/products", {
templateUrl: "app/products/productListView.html",
controller: "ProductListCtrl as vm"
})
.when("/products/create", {
templateUrl: "app/products/productCreateView.html",
controller: "ProductCreateCtrl as vm"
})
.when("/login", {
templateUrl: "app/login/login.html",
controller: "loginController as vm"
})
.otherwise({ redirectTo: "/products" });
$httpProvider.interceptors.push(function (appSettings, tokenContainer) {
return {
'request': function (config) {
// ToDo :
return config;
}
};
});
});
}());

Categories