cookie value not set in first time in angular js - angularjs

I want to get cookie value from one UI to another page.
That cookie value is user name.
EX:Nithya
When i logged to the home page the cookie value is empty the cookie value is set set after refreshing a page.
I want to set the cookie value when the load is load.
this is my home page Controller code
app.controller('homeCtrl',
function ($scope, $http, $window, $filter, $cookieStore) {
var logincheck = function () {
$http.get('loggedin').success(function (user) {
console.log(user);
$cookieStore.put('LoggedinUser', user);
$scope.LoggedinUsers = $cookieStore.get('LoggedinUser');
});
};
logincheck();
});
i am using the cookie in this code.
app.controller('RoleViewCtrlq', ['$scope', '$http', '$window', '$filter', '$cookieStore', '$notify', '$timeout',
function ($scope, $http, $window, $filter, $cookieStore, $notify, $timeout)
{
var username = $cookieStore.get('LoggedinUser');
}]);
can anyone give the solution..
Thanks

$cookiesStore is deprecated since v1.4.0 use $cookies instead
$cookies.put('LoggedinUser', user);
var username = $cookie.get('LoggedinUser');
And you should use then instead success . success and error deprecated too

Related

how to passing data from one controller to another controller using angular js 1

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
code Page1.html
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
now i want to show scope message into page2 controller
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
You can use $rootScope instead of $scope:
// do not forget to inject $rootScope as dependency
$rootScope.Message="Hi welcome";
But the best practice is using a service and share data and use it in any controller you want.
You should define a service and write getter/setter functions on this.
angular.module('app').service('msgService', function () {
var message;
this.setMsg = function (msg) {
message = msg;
};
this.getMsg = function () {
return message;
};
});
Now you should use the setMeg function in Controller1 and getMsg function in Controller2 after injecting the dependency like this.
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
$scope.Message="Hi welcome"
msgService.setMsg($scope.Message);
}]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
///here i want get that scope value
console.log('message from contoller 1 is : ', msgService.getMsg());
}]);
You should use services for it .
Services
app.factory('myService', function() {
var message= [];
return {
set: set,
get: get
}
function set(mes) {
message.push(mes)
}
function get() {
return message;
}
});
And in ctrl
ctrl1
$scope.message1= 'Hi';
myService.set($scope.message1);
ctrl2
var message = myService.get()
Sharing data from one controller to another using service
We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('Controller1', ['setGetData',function(setGetData) {
// To set the data from the one controller
$scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

controller and factory calling sequence differs while using $http?

I want to create a simple login, so I just created a html page with username and password. I created a controller and called a function called login and inside that I called a factory which returns a factory data, and I would create login based on that data.
Controller
myApp.controller('login', ['$scope','$rootScope', '$location', '$window', 'authenticate', '$http', '$cookieStore',function($scope, $rootScope, $location, $window, authenticate, $http, $cookieStore) {
$scope.alert = '';
$scope.login = function(){
authenticate.login($scope.login.username, $scope.login.password).then(function(response){
alert("Inside controller"+JSON.stringify(response));
});
}
}]);
My factory
myApp.factory('authenticate',['$http', '$filter', '$cookieStore', '$rootScope', '$window', '$q',
function($http, $filter, $cookieStore, $rootScope, $window, $q) {
var data = "";
var deferred = $q.defer();
return {
login: function(userName,password){
$http.post('user/serverside/authentication.php',{username: userName, password: password})
.then(function(response){
deferred.resolve(response.data);
alert("FACTORY"+JSON.stringify(response));
});
return deferred.promise;
}
}
}]);
I call the login function inside the controller on login,
The issue is when I logged in for
The first time with one data as expected first alert inside factory
executed and then the alert inside the controller is executed.
But on the second time alert inside controller executed first and the
factory alert displaying,
Doubts
Why the execution sequence change in the second time?
Is this a right way to use for login, if any better ways please
suggest?
I think the mistake its beacuse u should generate promise in every function and no in the main factory like:
myApp.factory('authenticate',['$http', '$filter', '$cookieStore', '$rootScope', '$window', '$q',
function($http, $filter, $cookieStore, $rootScope, $window, $q) {
var data = "";
return {
login: function(userName,password){
var deferred = $q.defer();
$http.post('user/serverside/authentication.php',{username: userName, password: password})
.then(function(response){
deferred.resolve(response.data);
alert("FACTORY"+JSON.stringify(response));
});
return deferred.promise;
}
}
}]);
Ur code not works because promise its generated first time executed and when code checked if promise its resolve automatically execute then block.
2.- You can use ssl to securize your login, but the function login its similar. The important its implementation its on server side.

AngularJS leave page

I use AngualrJS for my frontend, before navigating to a page in my routes.js there is a resolve where I can initialize variables needed for controller.
Actually I need the oposite of them - if I leave a page than a method should be invoked, because I use websocket/sockjs and I will switch of the ping if chat page is leaved.
Is there any possibility to do this?
Thanks a lot!
(function() {
'use strict';
angular
.module('myProject.chat')
.controller('ChatController', ChatController);
ChatController.$inject = ['$scope', '$state', '$location', '$http', '$timeout', ...];
function ChatController($scope, $state, $location, $http, $timeout, ...) {
$scope.vm = this;
var vm = this;
vm.stompClient.subscribe('/topic/chat/' ...
There is a destroy event you can use
$scope.$on('$destroy', function(){
// do cleanup
});

AngularJS Ionic: Unable to inject Ionic History

I am trying to inject ionic history in my Ionic Project and I am getting this error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.14/$injector/unpr?p0=%24ionicHistoryProvider%20%3C-%20%24ionicHistory
This is my complete controller code
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}])
Please what am doing wrong.
Are you using Cordova?
If you are, it is probably happening because you did not inject ngCordova in your module.
Like:
angular.module('anotei', ['ionic', 'ngCordova'])
my friend your problem is not in you $ionicHistory, it is in the locatStorage. you are not injecting the local storage in the controller. Just inject it and it will work.
Cheers.
Try to add the closing curly bracket } for the $scope.gotoLogouts function, just before the last line.
#Nadeem Khoury you should not inject localStorage. It is $localStorage that should be injected but he is using localStorage which should not be injected.
If this is exactly the code you are using, I am with #Ennedigi
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])
try to include timeout, location and windows in module
IonicModule
.factory('$ionicHistory', [
'$rootScope',
'$state',
'$location',
'$window',
'$timeout',
'$ionicViewSwitcher',
'$ionicNavViewDelegate',
function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
#Blaze, you have to inject $localStorage in your controller like below,
.controller('menu', ['$scope', '$state', '$ionicHistory', '$localStorage' function($scope,$state,$ionicHistory,$localStorage) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])

AngularJS $rootScope in factory - reload data

I have a factory calling a $resource. Upon refreshing the application entirely, this works as planned. But it not call the resource again throughout navigating the application. Ideally i would like the $resource called every time i call the factory from the controller.
app.factory("factoryList", function ($cookieStore, $resource, $http, $location, $window) {
var List = $resource('/api/list');
$http.defaults.headers.common['auth-token'] = $cookieStore.get("api_key") + ':' + $cookieStore.get("api_token");
return List.get();
});
This is my controller:
consoleApp.controller('mainController', function ($rootScope, $window, $scope, $resource, $http, $route, $location, $cookieStore, factoryList) {
$rootScope.list = factoryList;
});
Here is the fiddle I created
jsfiddle.net/HB7LU/5833/,
I can see the content updated between navigations

Resources