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*/
}
}
}
Related
Can't seem to get this factory to work properly.
I'm trying to do the $http requests from a factory.
But I'm getting this error of:
TypeError: PassFactory.setNewPass is not a function
Below is the code:
Factory
(function () {
angular
.module("myApp")
.factory('PassFactory', ['$http', function ($http) {
/*
var passFactory = {};
passFactory.setNewPass = function (newpass, user) {
return $http.post('/password/' + newpass, user, function (response) {
});
};
*/
return {
setNewPass: function (newpass, user) {
return $http.post('/password/' + newpass, user, function (response) {
});
}
};
}])
})();
Controller
(function () {
angular
.module("myApp")
.controller('PCtrl', ['$scope', '$location', '$rootScope', 'PassFactory', setHome]);
function setHome($scope, $location, PassFactory) {
$scope.login = function (user) {
if (user.newpassword == user.newpasswordconfirm) {
PassFactory.setNewPass(user.newpassword, user).then(function (response) {
$location.path("/");
});
}
};
}
})();
You have missed $rootScope in controller factory function. Always make sure the the order in dependency have been injected inside DI array, in same sequence you should ask for their instance inside its factory function.
angular
.module("myApp")
.controller('PCtrl', ['$scope', '$location', '$rootScope', 'PassFactory', setHome]);
//added $rootScope in 3rd place
function setHome($scope, $location, $rootScope, PassFactory) {
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
Im using gulp-concat to merge all angular js files into one but after running gulp task i get this error in chrome console on runing application :
angular.js:13708Error: [ng:areq] http://errors.angularjs.org/1.5.7/ng/areq?p0=userboxController&p1=not%20a%20function%2C%20got%20undefined
my gulp task :
gulp.task('scripts', function () {
return gulp.src(['js/app/*.js', 'components/*/*/*.js'])
.pipe(concat('appscript.js'))
.pipe(minify())
.pipe(gulp.dest('./dist/js/'));
});
and gulp-concat merges dedicated angular js files into appscript.js like:
angular.module('app',[]);
angular
.module("app", [])
.controller("paymentCtrl", ['$scope', '$http', function ($scope, $http) {
$http.get('data/payments.json').then(function (payments) {
$scope.payments = payments.data;
});
$scope.saveEntity = function () {
console.info("goog");
}
}]);
angular
.module("app",[])
.controller("userboxController", ['$scope', '$http',function ($scope, $http, usersService) {
usersService.getCurrentUser().then(function (user) {
$scope.user = user.data;
});
}]);
angular
.module("app",[])
.controller("usersController",['$scope', '$http','usersService', function ($scope, $http, usersService) {
usersService.getAll().then(function (users) {
$scope.users = users.data;
});
}]);
angular
.module("app", [])
.directive('usersGrid', function () {
return {
templateUrl : 'components/users/template/grid.html'
}
});
what's wrong with angular?!!
This is not a merge related problem.
You are making app modules every time with
angular.module('app', [])
You have to initialise module only one place and you will be using same module every time with ~ [] brackets.
Please find the plunker here
var myApp = angular.module('app');
myApp.controller("paymentCtrl", ['$scope', '$http', function($scope, $http) {
$http.get('data/payments.json').then(function(payments) {
$scope.payments = payments.data;
});
$scope.saveEntity = function() {
console.info("goog");
}
}]);
myApp.controller("userboxController", ['$scope', '$http', function($scope, $http, usersService) {
$scope.user = 'abc';
}]);
myApp.controller("usersController", ['$scope', '$http', 'usersService', function($scope, $http, usersService) {
usersService.getAll().then(function(users) {
$scope.users = users.data;
});
}]);
myApp.directive('usersGrid', function() {
return {
templateUrl: 'components/users/template/grid.html'
}
});
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
) {...})();
This is probably a matter of me not handling dependency injection proper, but I'm trying to make a 'Session' service available to my SessionsController. Here's my SessionsController:
angular.module('App.controllers').controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.foo = function() {
console.log("clicked foo..");
}
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save()
.success(function(data, status, headers, config) {
$cookieStore.put('_app_user', data);
});
}
};
$scope.destroy = function() {
$scope.session.$destroy();
};
}]);
Here's the actual Session service definition:
angular.module('App.services').service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = $cookieStore.get('_app_user');
this.signedIn = !!$cookieStore.get('_app_user');
this.signedOut = !this.signedIn;
this.userSession = new UserSession( { email:"foo#bar.com", password:"example", remember_me:true } );
//this.userRegistration = new UserRegistration( { email:"foo-" + Math.floor((Math.random()*10000)+1) + "#bar.com", password:"example", password_confirmation:"example" } );
$rootScope.$on('$routeChangeStart', function (current, next) {
if (this.signedOut && next !== '/login') {
console.log("relocating user..");
//$location('/login');
}});
}]);
And here's how I strung it together:
angular.module('App.resources', ['ngResource']);
angular.module('App.services', ['ngResource']);
angular.module('App.directives', []);
angular.module('App.filters', []);
angular.module('App.controllers', ['ngCookies', 'Session']);
var App = angular.module("App", ['App.resources', 'App.services', 'App.directives', 'App.filters', 'App.controllers', 'ui.compat', '$strap.directives', 'templates']);
Clearly missing something to string everything together as Firebug is complaining that there is no module named: Session.
Firebug is right, you have no module named session. You have a service named Session in the App.services module.
Just remove the Session module injection, and you are good to go.
angular.module('App.controllers', ['ngCookies']);