AngularJS Service Undefined When Injected - javascript

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

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

how to remove exclamation from routing of state url Mean full stack

I want to remove exclamation marks from url state routing like my url is now http://localhost:3000/#!/auth/register
i just want to remove this "!" marks from url after "#"
Is it possible to do? with mean.io
here is my app.js/system.js
'use strict';
//Setting up route
angular.module('mean').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// For unmatched routes:
//$urlRouterProvider.otherwise('/');
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/auth/login');
}
});
return deferred.promise;
};
// console.log($stateProvider);
// states for my app
$stateProvider
.state('tasks', {
url: '/kanban/:projectId/:projectSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve: {
loggedin: checkLoggedin,
onEnter: function($stateParams,$state, $uibModal) {
if ( $stateParams.projectId != "" ) {
updateTopMenu('Kanban','task','#!/kanban/'+$stateParams.projectId+'/'+$stateParams.projectSlug);
updateTopMenu('Schedule','schedule','#!/schedule');
}
}
}
}).state('home',{
url:'/',
templateUrl: 'projects/views/index.html',
controller: 'ProjectController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskEdit',{
url:'/kanban/:projectId/:projectSlug/:taskSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskAdd',{
url: "/task/taskAdd",
onEnter: function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: "system/views/include/model.html",
resolve: {},
controller: function($scope, $state, itemService) {
/*
$scope.state = $state.current;
$scope.params = $stateParams;
$scope.item = itemService.get($stateParams.id);
*/
$scope.ok = function () {
$scope.$close('clicked ok');
};
$scope.dismiss = function () {
$scope.$dismiss('clicked cancel');
};
}
}).result.then(function (result) {
// $scope.$close
alert('result ->' + result);
}, function (result) {
// $scope.$dismiss
return $state.transitionTo("home");
alert('dismiss ->' + result);
}).finally(function () {
// handle finally
return $state.transitionTo("tasks");
});
}
});
}
]).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
you have configured it here
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
remove this line to get ! removed from url
or enable html5mode using below code to remove # from url
$locationProvider.html5Mode(true);
but please read more about how url routes are handled in angular, and server side routing vs client side routing etc, before enabling html5mode
Change $locationProvider.hashPrefix('!'); to $locationProvider.hashPrefix('');
System.js
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);

Angular Routing not happening for Login screen

Following is my App.js code:
'use strict';
/* App Module */
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'phonecatControllers',
'phonecatFilters',
'phonecatServices'
]);
phonecatApp.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider.
when('/login', {
templateUrl: 'partials/login.html',
controller: 'PhoneLoginCtrl'
}).
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: 'PhoneListCtrl'
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: 'PhoneDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
}]);
Following is my Controller.js code:
'use strict';
/* Controllers */
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneLoginCtrl', ['$scope','$userInfoService','$location',
function($scope,$userInfoService,$location){
$scope.check = false;
$scope.message = null;
//$scope.user = {};
$scope.loginUser=function()
{
var username=$scope.user.name;
var password=$scope.user.password;
if(username=="admin" && password=="admin123")
{
//page.setUser($scope.user);
$location.path( "/phones" );
}
else
{
$scope.message="Error";
$scope.messagecolor="alert alert-danger";
}
}
}]);
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
function($scope, $routeParams, Phone) {
$scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
$scope.mainImageUrl = phone.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
Though my other functions are working - phone-list and phone-detail but login page is not appearing. When I am invoking login page blank page is appearing. Please help. Following is the link to my project in Plunker:
https://plnkr.co/edit/zKXSOyRBg5ks42VL3YM8

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

return data inside function but not view on html

var app = angular.module('app', ['ui.router','ngTasty']);
app.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: function($scope, $http, $location) {
$scope.getData = function(params) {
var dataUrl = 'main/home/?';
$scope.urlApiTwo = dataUrl + params;
return mydata($scope.urlApiTwo, $http);
};
}
});
}]);
function mydata(urxx, $http) {
return $http.get(urxx).then(function(response) {
return {
'rows': response.data.rows,
'header': response.data.header,
'pagination': response.data.pagination,
'abc': response.data.abc
};
});
}
I need to access "abc" data in home.html. but this is not view.
console log data:
{"header":[{"name":"Id"},{"name":"Subject"},{"name":"Status"}],"rows":[{"ids":"1","subject":"Hindi","status":"1"},{"ids":"2","subject":"English","status":"1"},{"ids":"3","subject":"Mathematics","status":"1"},{"ids":"4","subject":"Science","status":"1"},{"ids":"5","subject":"Social Science","status":"1"}],"pagination":{"count":"5","page":1,"pages":16,"size":80},"abc":[{"value":"home"}]}
When you retrieve data with $scope.getData use returned promise then method
$scope.getData(params).then(function(data) {
$scope.abc = data.abs;
});

Categories