Getting the dreaded module not instantiated error, but everything appears right - angularjs

I'm getting the error: "[$injector:modulerr] Failed to instantiate module myApp due to: ReferenceError: isUndefined is not defined". It suggests I misspelled something or forgot to included dependencies. I've checked and all my scripts are included, all my spelling is correct, and I don't think I've left any dependencies out. I've got a lot of other controllers structured very similarly to this one with no problem, but now two of my most recent added controllers/views are giving me the error. I stripped out all the logic to make sure I wasn't doing something inadvertent, but still no dice. I'm including the module it says is undefined, a similar controller that works, and the controller (now stripped of all logic except a console.log) for the new view that doesn't work. Any ideas?
The "undefined" module (with a number of logic taken out for brevity):
var app = angular.module("myApp", ["ngRoute", 'ngAnimate', 'angular-growl', 'ui.select', 'ngSanitize', 'ui.bootstrap', 'ui.bootstrap.datetimepicker']);
var HeaderCtl = function($scope, $location) {
console.log('inside HeaderCtl : ' + $scope.isLoggedIn);
$scope.tabSelected = function(tabname) {
console.log('Server Parameter :' + $scope.tabname);
$location.path("/" + $scope.tabname);
}
}
app.controller("HeaderCtl", ["$scope", "$location", 'growl', HeaderCtl]);
The similar working controller based on the module:
(function() {
var app = angular.module("myApp");
var loginController = function($scope, $rootScope, $http, $location, myApp, growl) {
// $scope.currenttab = $scope.isLoggedIn;
$scope.sendDt = function() {
$http.post('/login', {
username: $scope.user.username,
password: $scope.user.password,
})
.success(function(user) {
$rootScope.isLoggedIn = 'yes';
console.log('successfully logged in and redirecting to :');
$location.path("/");
$http.get('/getnavlist').success(function(list) {
if (list !== '0') { // got some menus
$rootScope.navlist = list;
$location.path("/" + list[0].value);
}
});
},
function() {
console.log('error in logging in');
$rootScope.message = 'user name or password is wrong';
$location.path("#/welcomeLogin");
});
}
};
app.controller("loginController", loginController);
}());
Finally, the error module with logic stripped out:
(function() {
var app = angular.module("myApp");
var signUpController = function($scope) {
$scope.formModel = {};
console.log("Woomp!");
}
app.controller("signUpController", signUpController);
}());

You can't inject angular module as injectable inside factory function. In loginController you had injected myApp(module name) as a dependency. This is root cause of your problem.
Change
//VVVVV//remove this
var loginController = function($scope, $rootScope, $http, $location, myApp, growl) {
to
var loginController = function($scope, $rootScope, $http, $location, growl) {

Related

Passing value between controllers in AngularJS

As stated in the title, I'm trying to pass a value (ID) from one controller (PerksApprovalController) going to another controller (PerksDetailsController). Please find below image for visual reference.
What I want to do is, when I click the "Show Details" button, it will redirect me to another page to display the details of the Control Number that I pass.
Below is my implementation.
Show Details Button Code
<button class="btn btn-xs" ng-click="vm.showDetails(p.ControlNumber)">Show Details</button>
PerksApprovalCtrl.js
(function () {
'use strict';
var app = angular.module('app');
PerksApprovalController.$inject = ['$window', 'app.perksService', 'app.sharedValuesFactory'];
app.controller('app.perksApprovalController', PerksApprovalController);
function PerksApprovalController($window, PerksService, SharedValuesFactory) {
/* jshint validthis:true */
var vm = this;
vm.showDetails = function (controlNo) {
SharedValuesFactory.setControlNo(controlNo);
$window.location = '/PerksDetails/PerksView';
}
}
})();
PerksDetailCtrl.js
(function () {
'use strict';
var app = angular.module('app');
PerksDetailController.$inject = ['$scope', '$http', '$q', '$window', 'app.perksService', 'app.sharedValuesFactory'];
app.controller('app.perksDetailController', PerksDetailController);
function PerksDetailController($scope, $http, $q, $window, PerksService, SharedValuesFactory) {
var vm = this;
PerksService.getPerksItems(SharedValuesFactory.getControlNo()).then(function (response) {
vm.perksItemDetails = response.data;
});
}
})();
I have created a service just like what they suggested in some topics here.
sharedValuesFactory.js
(function () {
'use strict';
var app = angular.module('app');
// SharedValuesFactory.$inject = ['$http'];
app.factory('app.sharedValuesFactory', SharedValuesFactory);
function SharedValuesFactory() {
var controlNoShared;
return {
setControlNo: function (c) {
this.controlNoShared = c;
},
getControlNo: function () {
return this.controlNoShared;
}
}
}
})();
My problem now is, everytime the details page is loaded, SharedValuesFactory.getControlNo() returns undefined. Looks like SharedValuesFactory is reset after the redirect or page load.
Any idea on how to properly pass a value from one controller to another?
TIA
I have a specific way of passing value in between Controllers. Hope it does the trick!
Note:
Not Sure what sharedValuesFactory.js is being used for! Assumming You are using this service to pass Data in between Controllers only. According to me only One service suites your requirement i.e PerksService.
The button passes the value (ID) of "ControlNumber".
<button class="btn btn-xs" ng-click="vm.showDetails(p.ControlNumber)">Show Details</button>
In PerksApprovalCtrl.js pass the controlNo you are getting on button click to the url of the page as in of a different view
PerksApprovalCtrl.js
(function () {
'use strict';
var app = angular.module('app');
PerksApprovalController.$inject = ['$window', 'app.perksService'];
app.controller('app.perksApprovalController', PerksApprovalController);
function PerksApprovalController($window, PerksService) {
/* jshint validthis:true */
var vm = this;
vm.showDetails = function (controlNo) {
$window.location = ;
$location.path('/PerksDetails/PerksView'+controlNo);
}
}
})();
In Routes.js or the place where you define the routes of your angular application add the following lines:
.when('/PerksDetails/PerksView/:controlNo', {
templateUrl: '<YOU DEFINE THE TEMPLATE>',
controller: 'PerksDetailController',
reloadOnSearch: false })
Here ":controlNo" is used to pass the value you are passing in the url from PerksApprovalController.
In PerksDetailController we get the controlNo from routeParams and pass it to your PerksService to get the details from it.
PerksDetailCtrl.js
(function () {
'use strict';
var app = angular.module('app');
PerksDetailController.$inject = ['$scope', '$http', '$q', '$window', '$routeParams', 'app.perksService'];
app.controller('app.perksDetailController', PerksDetailController);
function PerksDetailController($scope, $http, $q, $window, $routeParams, PerksService) {
var vm = this;
PerksService.getPerksItems($routeParams.controlNo).then(function (response) {
vm.perksItemDetails = response.data;
});
}
})();
Hope it Solves your problem! Thank You!

Angular Unit Testing Factory Injection

I've seen this answered but none of the solutions are working for me. I'm getting an error Error: [ng:areq] Argument 'fn' is not a function, got undefined which is causing my test to fail. What's the correct way to inject a factory into a test spec that isn't a stubbed factory.
login module
angular.module('loginModule', ['ui.bootstrap', 'permission', 'ui.router', 'coreModule', 'utilsModule']);
login controller
(function(){
'use strict';
angular.module('loginModule')
.controller('loginController', login);
login.$inject = [
'$log',
'$uibModal',
'$rootScope',
'storageFactory',
'loginFactory',
'$state',
'RoleStore',
'PermissionStore',
'vsmsCoreFactory'
];
function login($log, $uibModal, $rootScope, storageFactory, loginFactory, $state, RoleStore, PermissionStore, vsmsCoreFactory) {
/* jshint validthis: true */
var vm = this;
vm.loginUser = loginUser;
vm.forgotPassword = forgotPassword;
vm.errorCode = null;
PermissionStore.clearStore();
vsmsCoreFactory.getHashFunction()
.then(function(response) {
if(response) {
storageFactory.setHashFunction(response); // unknown provider
}
});
function loginUser() {
...
login controller spec
describe('loginController', function() {
var $controller;
beforeEach(module('loginModule'));
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('vm.loginUser', function() {
it('should be defined', function() {
var loginController = $controller('loginController');
expect(loginController.loginUser).toBeDefined();
});
});
});
unit test files
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep');
var paths = gulp.paths;
function runTests (singleRun, done) {
var bowerDeps = wiredep({
directory: 'bower_components',
exclude: ['bootstrap-sass-official'],
dependencies: true,
devDependencies: true
});
var testFiles = bowerDeps.js.concat([
'./src/components/scripts/ui-bootstrap-custom-tpls-2.1.3.js',
'./src/app/index.js',
'./src/{app,components}/**/*.module.js',
'./src/{app,components}/**/*.factory.js',
'./src/{app,components}/**/*.controller.js',
'./src/{app,components}/**/*.spec.js'
]);
gulp.src(testFiles)
.pipe($.karma({
configFile: 'karma.conf.js',
action: (singleRun)? 'run': 'watch'
}))
.on('error', function (err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
}
gulp.task('test', function (done) { runTests(true /* singleRun */, done) });
gulp.task('test:auto', function (done) { runTests(false /* singleRun */, done) });
app
'use strict';
angular.module('fotaAdminPortal',
[
'ngAnimate',
'ngCookies',
'ngTouch',
'ngSanitize',
'ngResource',
'ui.bootstrap',
'ui.router',
'ui.router.stateHelper',
'pascalprecht.translate',
'utilsModule',
'loginModule',
...
])
log
Chrome 54.0.2840 (Mac OS X 10.11.6) loginController vm.loginUser should be defined FAILED
Error: [$injector:unpr] Unknown provider: storageFactoryProvider <- storageFactory <- loginController
The fotaAdminPortal module isn't loaded for the test so vsmsCoreFactory never gets registered.
Also there's no need to manually pass services into a controller as the injector will automatically do this when you create it. Passing services manually is useful when you need to pass something that isn't a globally registered service ie $scope or mock a service for a single controller instance.
Atm the mocks for the factories are just an undefined variable which will cause errors when the logic depending on them tries to call the methods that don't exist. You'll need to properly stub any methods on these mocks. But leaving those aside for the moment your test should be something like:
describe('loginController', function() {
var $controller;
beforeEach(module('fotaAdminPortal'));
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('vm.loginUser', function() {
it('should be defined', function() {
var loginController = $controller('loginController');
expect(loginController.loginUser).toBeDefined();
});
});
});
If you want to load loginModule in isolation then you need to extract vsmsCoreFactory into another module and add that as a dependency:
angular.module('vsmsCore', [])
.factory('vsmsCoreFactory', function($http, env, $log, storageFactory) {
});
angular.module('loginModule', ['ui.bootstrap', 'permission', 'ui.router', 'vsmsCore']);
Then you can do beforeEach(module('loginModule')) instead

Angular - DI dependency injection the connection between different Modules and service\directive from another module

If I need a to use a factory from another module do I need to add first the DI of the module to my current module and after that add the DI of the factory to the current factory? Or can I just add the factory itself (without its module)?
So if above its true the only use of Di in modules is for that use... or am i missing something else?
var myApp = angular.module('myApp', []);
myApp.service('myService', function() {
// do some stuff
});
myApp.controller('otherCtrl', function($scope, myService) {
// do some stuff
});
inject myApp module into otherApp module and use service myService:
var otherApp = angular.module('otherApp', ['myApp']);
otherApp.controller('myCtrl', function($scope, myService) {
$scope.myService = myService;
});
declare modules with dependecies.
var baseApp = angular.module("ERMSApp", ['ngSanitize', 'ngRoute', 'ngTable']);
var baseApp1 = angular.module("ERMSApp1", ['ERMSApp', 'ngSanitize', 'ngRoute', 'ngTable']);
declaring service.
baseApp.factory("getEmployeesService", function ($http) {
var promise;
var getEmployeesService = {
getEmployees: function () {
if (!promise) {
var promise = $http.get("/Timesheet/GetEmployees").then(function (result) {
return result;
});
}
return promise;
}
}
return getEmployeesService;
});
using service in another module
baseApp1.controller("leaveOnBehalfCtrl", function ($scope, $http, $filter, $sce, ngTableParams, $compile, getEmployeesService) {
getEmployeesService.getEmployees().then(function (data) {
$scope.employees = data.data;
})
});

Error: error:unpr Unknown Provider

MY MAIN CONTROLLER
var MyApp = angular.module('ionicApp', ['ionic', 'MobiNav', 'authFactory']);
CONTROLLER CONSUMING FACTORY
MyApp.controller('AuthUser', ['$scope', 'authFactoryService', function ($scope, authFactoryService) {
$scope.showForm = true;
$scope.UserDataLogin = function () {
var loginData = {};
$scope.registration = {
userName: $scope.Auth.userName,
password: $scope.Auth.password,
confirmPassword: $scope.Auth.password
};
authFactoryService.SaveRegistration(registration);
window.scope = loginData;
};
}
]
);
THIS IS THE FACTORY IN SEPERATE FILE
var AuthService = angular.module('authFactory', []);
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {
return {
SaveRegistration: function() {
var urlBase = 'http://localhost:48868/';
$http.post(urlBase + 'api/account/register', registration).then(function(response) {
$scope.savedSuccessfully = true;
$scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
},
function(response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
}]);
error what i'm getting
Error: [$injector:unpr] http://errors.angularjs.org/1.2.17/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20authFactoryService
at Error (native)
why it is unable to load authFactoryService service
Finally Figured the dug,
$scope was again injected in Factory
replaced
this
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {}]);
to this (just removed the $scope which was again injected in factory for dependency.
AuthService.factory('authFactoryService', [
'$http', '$q', function ($http, $q, $scope) {}]);
var AuthService = angular.module('authFactory', []);
You indlcuded the an empty array in your module. This makes it a
module setter, overwriting an existing module.
to fetch a module you use angular.module('authFactory') <-- note the missing second parameter.
Regards
Sander

Can't figure out how to use angularFireCollection in my service

I must be missing something very simple. I've seen a bunch of examples of angularFireCollection but no examples using in the way i'm using it in a service (perhaps that's the issue?). here's my code which is getting an angular injection error unknown provider:
angular.module('CommentBoxService', [])
.service('CommentBoxSvc', ['$rootScope', '$stateParams', '$http', '$location','angularFireCollection',
function ($rootScope, $stateParams, $http, $location, $firebase, angularFireCollection) {
var commentFireBase = null;
var user; var type;
var getFireBaseRef = function () {
user = ($location.absUrl().split('/'))[4].replace('#', '');
getType();
commentFireBase = angularFireCollection('https://XXX/users/' + user + '/comment-boxes/' + type);
return commentFireBase;
}
return {
getFireBaseRef : getFireBaseRef
}
}]);
am i missing something with the injection method?

Resources