AddDevicemodalCtrl is not a function, got undefined - javascript

I am getting the error noted above, I believe this is because the controller is not attached to the module properly, however I could be wrong. Here is the controller that has been defined.
(function () {
'use strict';
angular
.module('WS')
.controller('AddDeviceModalCtrl', AddDeviceModalCtrl);
/* #ngInject */
function AddDeviceModalCtrl(
$rootScope,
$scope,
$stateParams,
close,
Auth,
device,
DeviceAPI,
PathfinderAPI,
helpers,
GLOBAL_CONST,
Notification
) {...})();
I click a button on the web page and it hits this controller and hits the openModal function. The Modal object is a service which is defined below.
(function() {
'use strict';
angular
.module('WS.environment')
.controller('DevicesCtrl', DevicesCtrl);
/* #ngInject */
function DevicesCtrl($rootScope, $scope, $state, $stateParams, DeviceAPI, helpers, GLOBAL_CONST, Modal) {
angular.extend($scope, {
openModal: openModal,
editDevice: editDevice
});
angular.extend($scope, {
devices: [],
errors: []
});
$rootScope.$on('deviceAdded', onUpdateDeviceList);
DeviceAPI
.getDevices()
.then(onGetDeviceListSuccess);
function onGetDeviceListSuccess(devices) {
$scope.devices = devices;
}
$rootScope.$on('updateDevicesEvent', function(event, devices) {
onGetDeviceListSuccess(devices);
});
function openModal($event) {
Modal.showAddDevice($scope.device);
}
function editDevice($event, device) {
Modal.showEditDevice(device);
}
function onUpdateDeviceList($event, device) {
$scope.devices.push(device.device);
}
}
})();
here is my service:
(function() {
'use strict';
angular
.module('WS.service')
.factory('Modal', Modal);
/* #ngInject */
function Modal($rootScope, ModalService) {
var service = {
showAddDevice: showAddDevice,
showEditDevice: showEditDevice,
showConfirmation: showConfirmation,
showTimeRange: showTimeRange
};
return service;
function showAddDevice(device) {
$rootScope.modalHasOpen = true;
return ModalService.showModal({
templateUrl: 'modules/modals/device/add/views/device.html',
controller: 'AddDeviceModalCtrl',
inputs: {
device: device
}
});
}})();
and this is my app:
WS.app = angular
.module('WS', [
'interceptors',
'WS.common',
'WS.account',
'WS.layout',
'WS.dashboard',
'WS.environment',
'WS.service',
'WS.settings'
])
.config(config)
.run(run);

It seems that 'WS' module was not available when you added AddDeviceModalCtrl controller to it.
Take a note that you will have to make sure that angular module is ready before adding any controller or service over it.
Try the below code in a single file:
(function () {
'use strict';
WS.app = angular
.module('WS', [
'interceptors',
'WS.common',
'WS.account',
'WS.layout',
'WS.dashboard',
'WS.environment',
'WS.service',
'WS.settings'
])
.config(config)
.run(run);
angular
.module('WS')
.controller('AddDeviceModalCtrl', AddDeviceModalCtrl);
/* #ngInject */
function AddDeviceModalCtrl(
$rootScope,
$scope,
$stateParams,
close,
Auth,
device,
DeviceAPI,
PathfinderAPI,
helpers,
GLOBAL_CONST,
Notification
) {...})();

Related

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

AngularJs: use cookies inside custom service

I tried to use angular cookies in custom service, but got the error:
Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService
I store module, controllers and services in separate files.
Controller:
(function() {
'use strict';
angular
.module('app')
.controller('AuthController', AuthController);
AuthController.$inject = ['$scope', '$http', '$location', 'checkLoginService'];
function AuthController($scope, $http, $location, checkLoginService) {
/* jshint validthis:true */
var vm = this;
vm.title = 'AuthController';
$scope.login = function(user) {
/*logic*/
}
$scope.checklogin = function () {
if (checkLoginService.checkLogin()) {
/*logic*/
}
}
$scope.checklogin();
}
})();
Service:
(function () {
'use strict';
angular
.module('app')
.service('checkLoginService', ['ngCookies', checkLoginService]);
checkLoginService.$inject = ['$http'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}
})();
ngCookies is module not a dependency name, you should inject ngCookies in module dependency and use $cookies to get cookie object
//somewhere in app.js
angular.module('app', ['otherModules', ..... , 'ngCookies'])
Also add $cookies missing dependency inside a checkLoginService $inject array.
angular.module('app')
.service('checkLoginService', ['$cookies', checkLoginService]);
checkLoginService.$inject = ['$http', '$cookies'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}

Trouble with Angular Resource Injection

I'm getting started with the meanjs stack, and have reached a bit of a headscratcher that I don't have the understanding to google properly.
I have the following files:
**
(function () {
'use strict';
angular
.module('students')
.controller('StudentsListController', StudentsListController);
StudentsListController.$inject = ['StudentsService'];
function StudentsListController(StudentsService) {
var vm = this;
vm.students = StudentsService.query();
}
}());
Using this service, I am able to get an array of Student objects in the list-students controller, next:
list-students.client.controller.js
(function () {
'use strict';
angular
.module('students')
.factory('StudentsService', StudentsService);
StudentsService.$inject = ['$resource'];
function StudentsService($resource) {
return $resource('api/students/:studentId', {
studentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
This works as intended.
What I don't understand, is why when I try to use the same service in another controller, it seems to fail to inject, leaving me with an undefined StudentsServices variable.
What gives?
students.client.controller.js
(function () {
'use strict';
// Students controller
angular
.module('students')
.controller('StudentsController', StudentsController);
StudentsController.$inject = ['$scope', '$state', 'Authentication', 'StudentsService'];
function StudentsController ($scope, $state, Authentication, student, StudentsService) {
var vm = this;
vm.authentication = Authentication;
vm.student = student;
vm.students = StudentsService.query();
...
}());
Your inject is wrong.
'$scope', '$state', 'Authentication', 'StudentsService'
But you're telling the controller to expect
$scope, $state, Authentication, student, StudentsService
I figured it out, per
AngularJS: Factory is always undefined when injected in controller
It was that my injections need to be in the same order as the params passed into the controller function.
Aha!

angularjs navigate to route from factory/service

Why $location.url( "/messages" ); is not working? is there any restriction about $location inside a factory in AngularJS? any idea what is going on?
If I'm doing something wrong can you please tell my how should I redirect to another url "/messages"? I can't reload the page using so $window is not an option.
Thanks
My factory:
(function () {
'use strict';
angular
.module('app.conversation')
.factory('conversationFactory', conversation);
conversation.$inject = ['$rootScope', '$q', 'authFactory', '$location'];
function conversation($rootScope, $q, authFactory, $location) {
var service = {
changeLocation: changeLocation
};
return service;
function changeLocation() {
$location.url( "/messages" ); // recarga MIERDA!!!!!
}
}
})();
Route works fine:
(function () {
'use strict';
angular
.module('app.messages')
.config(configFunction);
configFunction.$inject = ['$routeProvider'];
function configFunction($routeProvider) {
$routeProvider
.when('/messages', {
templateUrl: 'app/messages/messages.html',
controller: 'messagesController',
controllerAs: 'meC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
}).when('/compose/:to?', {
templateUrl: 'app/messages/compose.html',
controller: 'composeController',
controllerAs: 'mcC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
});
}
})();
use $location.path( "/messages" );
I did:
$location.path( "/messages" ); // and then
$rootScope.$apply()
$location.path doesn't change in a factory with AngularJS

10 digest() iteration reached error in login procedure

This is my code to implement in my application a login procedure. The application has to verify the cookie set by the server and continue with the login procedure by redirect the user to canvas state. My issue is that I get the above mentioned error. Actually it works that is the login is made successfully but I would like to get rid of this error. I guess that the error should be in the $stateChangeStart but I don't know how to fix it. any idea?
(function() {
'use strict';
angular
.module('app', [
'ui.router',
'ngResource',
'ngCookies',
'app.login'
])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/login');
})
.run(function($rootScope, AuthService, RedirectService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (!AuthService.isAuthenticated()) {
// the user isn't authenticated
event.preventDefault();
// redirect to the server side
RedirectService.redirectToAuth();
}
});
});
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('AuthService', Auth);
Auth.$inject = ['Cookie', 'Session'];
function Auth(Cookie, Session) {
return {
login: function(params) {
// here set the session with params passed by the server
Session.create(params.id, params.data.id, params.data.make, params.data.name);
},
isAuthenticated: function() {
// check cookie here set in the server side
return Cookie.exist();
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.service('Cookie', Cookie);
Cookie.$inject = ['$cookies'];
function Cookie($cookies) {
this.authCookie = $cookies.__cookie;
this.exist = function() {
return (this.authCookie ? true : false);
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('RedirectService', Redirect);
Redirect.$inject = ['$window'];
function Redirect($window) {
return {
redirectToAuth: function() {
// redirect the user to the server for auth
$window.location.href = "http://" + $window.location.host + "/auth/facebook";
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.controller('LoginController', Login);
// here inject what function Login needs
Login.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AuthService'];
function Login($rootScope, $scope, $state, $stateParams, AuthService) {
var params = {
id: $stateParams.userid,
data: {
id: $stateParams.modelid,
make: $stateParams.modelmake,
name: $stateParams.modelname
}
};
$scope.login = function(params) {
AuthService.login(params);
// activate the canvas state
$state.go('canvas');
};
// run the login function to set the Session user with data passed by the server
$scope.login(params);
}
})();
Maybe this can help a little more:
/*
We are using the below urlRouterProvider.otherwise() because of:
https://github.com/angular-ui/ui-router/issues/600
*/
$urlRouterProvider.otherwise(function($injector, $location) {
var $state = $injector.get('$state');
$state.go('login');
});
With this code you can still use the otherwise(), the disadvantage of using when() is that other unknown routes will not match. Above code solved all of our infinite loops.
Fixed the issue
$urlRouterProvider.otherwise('/login');
caused all this issue.
removed it and replaced with when() solved the issue

Categories

Resources