AngularJS page reloading before $state.go - angularjs

I'm following this tutorial .. First time I execute function (fazerLogin) from ng-click, after set cookies, I don't know why, it is reloading current state before $state.go function. When button activates fazerLogin function(first time only), it executes all the code, but before my $state.go('temperatura'), it "reloads" the same state, executing my function initController() and cleaning all credentials. If I try to login again, it works perfectly. And if I'm logged and I go to state login again, it works, without any of this problem. There is my code
LoginController:
app.controller('LoginController', function($timeout, $rootScope, $location, $scope, $cookies, $state, AuthService){
(function initController() {
AuthService.LimparCredenciais();
})();
$scope.fazerLogin = function () {
if(angular.isUndefined($scope.login)){
swal("Preencha o campo 'Login'");
$('#usuario').focus();
}else if(angular.isUndefined($scope.senha)){
swal("Preencha o campo 'Senha'");
$('#senha').focus();
}else{
$scope.usuario = {login: $scope.login, senha: $scope.senha};
AuthService.Login($scope.usuario, function(response) {
if(response != null) {
if(!response.status){
swal("Login ou senha incorretos!");
}else{
//HERE IS THE PROBLEM THAT IS RELOADING CURRENT PAGE
AuthService.AtualizarCredenciais(response.usuario);
$state.go('temperatura');
}
} else {
swal("ERRO");
}
});
}
};
});
And my app.js:
var app = angular.module('app', [ 'ui.router', 'ui.materialize', 'ngResource', 'angularUtils.directives.dirPagination', 'ngCookies', 'zingchart-angularjs']);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
// $urlRouterProvider.otherwise('login');
$stateProvider.state('login', {
url: "/login",
templateUrl: "pages/login.html",
controller: "LoginController"
})
});
app.run(function($cookies, $rootScope, $location, $state, $cookies, $timeout) {
$rootScope.baseUrl = window.location.origin + window.location.pathname;
// keep user logged in after page refresh
$rootScope.global = $cookies.get('global') || {};
$rootScope.$on('$locationChangeStart', function(event, next, current) {
// redirect to login page if not logged in
if ($location.path() !== '/login' && angular.isUndefined($rootScope.global.usuario)
&& $location.path() !== '/cadastro') {
$state.go('login');
}
});
});
In my AuthService, there is my code:
angular.module("app").factory(
"AuthService",
function(Base64, $http, $cookies, $rootScope, $timeout, Usuario, $state) {
var service = {}
service.Login = function(usuario, callback) {
Usuario.logar(usuario)
.success(function(data) {
callback(data);
}).error(function(erro) {
// $state.go('erro');
});
};
service.AtualizarCredenciais = function(usuario) {
console.log("atualizando credenciais");
var key = Base64.encode(usuario.login + ':' + usuario.senha);
$rootScope.global = {
usuario : {
login : usuario.login,
key : key,
id : usuario.id
}
};
$cookies.put('global', $rootScope.global);
console.log('setou cookies');
//AFTER SET COOKIES, IT IS RELOADING CURRENT STATE AND EXECUTING METHOD TO CLEAR CURRENT CREDENTIALS
};
service.LimparCredenciais = function() {
console.log("limpando credenciais");
$rootScope.global = {};
$cookies.remove('global');
};
return service;
});
In my login.html:
<div class="row">
<div class="input-field col s12">
<a ng-click="fazerLogin()" class="btn waves-effect waves-light col s12">Login</a>
</div>
</div>
In my Usuario.js, there are only posts to my php files to get some data from database.

Related

How to handle $rootscope and take user id of logged in user in AngularJS?

I want to find the ID of the logged in user and display it in a page. I am new to angular and I don't have much clue on how to handle a session..
I have an angular app which is connected to backend API (.net core).
I will show the instances where $rootScope is used in the website (login and authorization is already enabled). I need to get an understanding of this to learn the app.
In App.js :
//Run phase
myApp.run(function($rootScope, $state) {
$rootScope.$state = $state; //Get state info in view
//Should below code be using rootScope or localStorage.. Check which one is better and why.
if (window.sessionStorage["userInfo"]) {
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}
//Check session and redirect to specific page
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
if(toState && toState.data && toState.data.auth && !window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#login";
}
if(!toState && !toState.data && !toState.data.auth && window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#dashboard";
}
});
});
Users.js :
'use strict';
angular.module('users', []);
//Routers
myApp.config(function($stateProvider) {
//Login
$stateProvider.state('login', {
url: "/login",
templateUrl: 'partials/users/login.html',
controller: 'loginController'
});
//Factories
myApp.factory('userServices', ['$http', function($http) {
var factoryDefinitions = {
login: function (loginReq) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
}
}
return factoryDefinitions;
}
]);
//Controllers
myApp.controller('loginController', ['$scope', 'userServices', '$location', '$rootScope', function($scope, userServices, $location, $rootScope) {
$scope.doLogin = function() {
if ($scope.loginForm.$valid) {
userServices.login($scope.login).then(function(result){
$scope.data = result;
if (!result.error) {
window.sessionStorage["userInfo"] = JSON.stringify(result.data);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
//$localStorage.currentUser = { username: login.username, token: result.data };
//$http.defaults.headers.common.Authorization = 'Token ' + response.token;
$location.path("/dashboard");
}
});
}
};
}]);
I came to know that the information about the user will be available in $rootScope.userInfo. If so, how can I take a value inside it?
Please explain with an example if possible. Thanks in advance.
One:
myApp.controller('loginController', [
'$scope', 'userServices', '$location',
'$rootScope',
function($scope, userServices, $location, $rootScope) {
Inside the controller, $rootScope was injected which makes you have access to the userInfo in that controller.
so if you inject $rootScope into another controller and console.log($rootScope.userInfo) you would see the users data.
myApp.controller('anotherController', ['$scope', '$rootScope', function
($scope, $rootScope){
console.log($rootScope.userInfo) //you'd see the users data from sessionStorage
});
According to this post on quora
$scope is an object that is accessible from current component
e.g Controller, Service only. $rootScope refers to an object
which is accessible from everywhere of the application.
You can think $rootScope as global variable and $scope as local variables.
$rootScope Defn.
In your case, once the user is logged in a key "userInfo" in sessionStorage is created and the same data is copied to $rootScope.userInfo. To check the fields in the userInfo after login try
console.log($rootScope.userInfo);
and print it in the console or open your session storage in your browser debugger tools [for chrome open developer tools>applications>sessionstorage>domainname] to view the values in the "userInfo" key.
Suppose you have
{
uid: "10",
fullname: "John Doe"
}
you can access uid in the script using $rootScope.userInfo.uid or $rootScope.userInfo['uid'].
Just in case you are unable to read the code, here is an explanation
if (window.sessionStorage["userInfo"]) {
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}
is checking the user is logged in or not.
the factory
myApp.factory('userServices', ['$http', function($http) {
var factoryDefinitions = {
login: function (loginReq) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
}
}
is calling the server to get the userInfo object.
$scope.doLogin = function() {
if ($scope.loginForm.$valid) {
userServices.login($scope.login).then(function(result){
$scope.data = result;
if (!result.error) {
window.sessionStorage["userInfo"] = JSON.stringify(result.data);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
//$localStorage.currentUser = { username: login.username, token: result.data };
//$http.defaults.headers.common.Authorization = 'Token ' + response.token;
$location.path("/dashboard");
}
});
}
};
$scope.doLogin is calling the above factory and storing the userInfo object.

View not updating upon form submit

This is a basic weather app that grabs info from an open weather API. Upon loading, it gets the weather information for the default city and I'm able to successfully log the returned info to the console, however my view doesn't update until I switch to a different view and then back. I feel like a $scope.$apply needs to go somewhere, but I couldn't get it working anywhere I tried.
App:
var weather = angular.module('weather', ['ngRoute', 'ngResource', 'ui.router']);
weather.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/overview');
$stateProvider
.state('overview', {
url: '/overview',
templateUrl: 'pages/overview.html',
controller: 'overviewController'
})
.state('forecast', {
url: '/forecast',
templateUrl: 'pages/forecast.html'
})
.state('details', {
url: '/details',
templateUrl: 'pages/details.html'
})
});
weather.controller('homeController', ['$scope', '$location', '$resource', 'weatherService', function($scope, $location, $resource, weatherService) {
$scope.txtCity = weatherService.city;
$scope.submit = function() {
weatherService.city = $scope.txtCity;
weatherService.getForecast(weatherService.city, function(x){
weatherService.currentForecast = x;
// TESTING
console.log(x);
});
};
// Run the submit function initially to retrieve weather data for the default city
$scope.submit();
// Function to determine the active tab, sets its class as "active"
$scope.isActive = function (path) {
return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}
}]);
weather.controller('overviewController', ['$scope', '$filter', 'weatherService', function($scope, $filter, weatherService) {
$scope.currentForecast = weatherService.currentForecast;
// Kelvin to Fahrenheit
$scope.convertTemp = function(temp) {
return Math.round((1.8*(temp - 273))+32);
}
$scope.convertToDate = function(dt) {
var date = new Date(dt * 1000);
return ($filter('date')(date, 'EEEE, MMM d, y'));
};
}]);
weather.service('weatherService', function($resource, $http){
this.currentForecast = null;
// default city
this.city = 'Chicago, IL';
this.getForecast = function(location, successcb) {
$http({
method : "GET",
url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
}).success(function(data){
successcb(data);
}).error(function(){
});
}
});
overview.html (view):
<h4>Daily</h4>
<ul>
<li ng-repeat="w in currentForecast.list">{{ convertToDate(w.dt) }} {{ convertTemp(w.temp.day) }}°</li>
</ul>
Submit form:
<form ng-submit="submit()">
<button type="submit" class="btn btn-primary btn-sm">Get Forecast</button>
<input type="text" ng-model="txtCity">
</form>
Change your service function to:
this.getForecast = = function(location) {
return $http({
method : "GET",
url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
}).then(
function(response) {
return response.data;
}
)
};
And in your controller, use it like this in the submit function:
weatherService.getForecast(weatherService.city).then(
function(data) {
weatherService.currentForecast = data;
console.log(data);
}
);
This allows you to handle the success function of the $http promise directly from the controller. Currently you're passing the function to the service, and it doesn't know what the weatherServiceparameter is, because it outside of the service scope (It's avalable in the controller).
Now, in your overviewController controller, you can watch for changes inside the service like this:
$scope.$watch(function() { return weatherService.currentForecast; },
function(newVal) {
if(!newVal) return;
$scope.currentForecast = newVal;
}, true);

Browser reload doesn't reload current Angular view

The problem I'm having is that after a user logs-in or signs-up they are redirected to the games view, this happens within the createUser function or after a successful authentication; in either case the redirect is handled with $state.go('games').
This all works fine, however, if the user navigates away from the games view to any other state like createGame or dashBoard and then refreshes the browser in one of those views they are always redirected back to the games view. When I remove the $state.go('games') this doesn't happen, and reload will only reload the current view (like it should).
I have tried changing parameters on $state.go and tried using $state.transitionTo(), but nothing changes this behavior.
Is this just normal behavior for $state.go? If not, am I using it wrong, and are there other ways to redirect? What can I do to stop this behavior?
var game = angular.module('game', ['ui.router','firebase']);
game.config(['$stateProvider', '$locationProvider', function($stateProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider.state('signUp', {
url: '/signUp',
templateUrl: '/templates/signUp.html'
});
$stateProvider.state('games', {
url: '/games',
templateUrl: '/templates/games.html',
controller: 'games.controller'
});
$stateProvider.state('login', {
url: '/login',
templateUrl: '/templates/login.html'
});
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: '/templates/dashboard.html',
controller: 'dashboard.controller'
});
$stateProvider.state('createGame', {
url: '/createGame',
templateUrl: '/templates/createGame.html',
controller: 'createGame.controller'
});
}]);
// Root reference to database
game.factory("Fire", function($firebaseAuth) {
var ref = new Firebase("https://money-game.firebaseIO.com/");
return ref;
});
// Gives access to auth methods
game.factory("Auth", ["$firebaseAuth", "Fire",
function($firebaseAuth, fire) {
return $firebaseAuth(fire);
}
]);
game.controller('app.controller', ['$scope', '$state', '$stateParams', 'Auth', 'Fire', function ($scope, $state, $stateParams, auth, fire) {
$scope.user = {
email : '',
password : ''
};
$scope.signUp = function() {
auth.$createUser($scope.user)
.then(function(userData) {
// After successful signup save a user record to users under their auth ID
fire.child('users').child(userData.uid).set({
name : $scope.user.name,
email : $scope.user.email,
joined : Date.now()
});
$state.go('games');
console.log("User " + userData.uid + " created successfully!");
})
.catch(function(error) {
console.error("Error: ", error);
});
};
$scope.login = function() {
auth.$authWithPassword($scope.user).catch(function(error) {
console.error("Authentication failed:", error);
});
};
$scope.logout = function() {
auth.$unauth();
window.location = '/';
};
auth.$onAuth(function(authData) {
if (authData) {
$scope.activeUser = authData;
// After user logs in find user record by auth id
fire.child('users').child(authData.uid).on('value', function(snapshot) {
// Checks if user exsists
if (snapshot.exists()) {
// sets scope user to the user data
$scope.user = snapshot.val();
// sets scope user id to the auth id
$scope.user.id = snapshot.key();
}
});
console.log("Logged in as:", authData.uid);
$state.go('games');
} else {
$scope.activeUser = false;
// $scope.user = '';
}
});
}]);
game.controller('games.controller', ['$scope', '$state', '$stateParams', 'Auth', '$firebaseArray','Fire', function ($scope, $state, $stateParams, auth, $firebaseArray, fire) {
$scope.games = $firebaseArray(fire.child('games'));
$scope.view = 'listView';
$scope.setCurrentGame = function(game) {
$scope.currentGame = game;
};
$scope.addPlayer = function(game) {
console.log(game.$id);
var ref = fire.child('players').child(game.$id);
ref.push({
id : $scope.user.id,
name : $scope.user.name,
email : $scope.user.email
})
};
// swap DOM structure in games state
$scope.changeView = function(view){
$scope.view = view;
}
}]);
game.controller('createGame.controller', ['$scope', '$state', '$stateParams', 'Auth', '$firebaseArray','Fire', function ($scope, $state, $stateParams, auth, $firebaseArray, fire) {
$scope.games = $firebaseArray(fire.child('games'));
$scope.createGame = function() {
if ($scope.format == 'Match Play') {
$scope.skinAmount = 'DOES NOT APPLY';
$scope.birdieAmount = 'DOES NOT APPLY';
}
$scope.games.$add({
name: $scope.gameName,
host: $scope.user.name,
date: $scope.gameDate,
location: {
course: $scope.courseName,
address: $scope.courseAddress
},
rules: {
amount: $scope.gameAmount,
perSkin: $scope.skinAmount,
perBirdie: $scope.birdieAmount,
format: $scope.format,
holes : $scope.holes,
time: $scope.time
}
})
// $state.go('games');
};
}]);
It's not about $state.go
It's actually about when you call it, $state.go does one simple thing : trigger a change in the routing state off your application. You just happen to do it everytime your application authenticates your user against your $firebaseAuth service, in the $onAuth handler.
A single page app is an app
When you refresh the page in the browser, the entire app reloads, starts again, boostraps everything to display your app. This startup process includes re-authenticating your user (I didn't quite see where it is done in your code, but it has to be done), thus triggering the $onAuth handler again… and ultimately execute $state.go('games') again.
Put your $state.go invocation elsewhere
You don't actually mean to do it every time your app authenticates the user, you rather want to do it when your user performs a successful login or sign-up action.
$authWithPassword returns a promise, you could do the state change in a success callback when the promise is resolved.
Hope that helps !

How to prevent the need login everytime without logout in Ionic App?

How I can make my Ionic App to prevent the need login everytime after exit app or back to background without logout ?
Its my source code:
login.js
angular.module('starter.controllers')
.controller('LoginCtrl', ['$scope', '$rootScope', '$location', '$localStorage', '$q', '$http', '$window', '$state', 'AuthFac tory', 'SessionFactory',
function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {
$scope.login = {
email: null,
password: null
};
$scope.login = function() {
$rootScope.showLoading("Authenticating..");
var email = $scope.login.email,
password = $scope.login.password;
if (email !== undefined && password !== undefined) {
AuthFactory.login(email, password).success(function(data, status, headers, config) {
if (data.success === false) {
$rootScope.hideLoading();
$rootScope.toast('Invalid Credentials');
} else {
SessionFactory.isLogged = true;
SessionFactory.user = data.data.username;
SessionFactory.userRole = data.data.name;
$localStorage.id = data.data.id;
$localStorage.token = data.data.token;
$window.sessionStorage.token = data.data.token;
console.log($window.sessionStorage.token);
$localStorage.user = data.data.username; // to fetch the user details on refresh
console.log($localStorage.user);
$localStorage.userRole = data.data.name; // to fetch the user details on refresh
console.log($localStorage.userRole);
} //end else data.success
}).error(function(data, status, headers, config) {
if (status === 500) {
$rootScope.hideLoading();
$rootScope.toast('Invalid Email');
}
});
}
};
}
]);
authfactory.js
angular.module('starter.factories')
.factory('SessionFactory', function($window, $localStorage) {
var auth = {
isLogged: false,
check: function() {
if ($localStorage.token && $localStorage.user ) {
this.isLogged = true;
} else {
this.isLogged = false;
delete this.user;
}
}
}
return auth;
})
.factory('AuthFactory', function($window, $location, $http, SessionFactory, $localStorage) {
return {
login: function(email, password) {
return $http.post('url', {
email : email,
password: password
});
},
logout: function() {
if (SessionFactory.isLogged) {
SessionFactory.isLogged = false;
delete SessionFactory.user;
delete SessionFactory.userRole;
delete $localStorage.token;
delete $localStorage.user ;
delete $window.sessionStorage.userRole;
$location.path("/login");
}
}
}
})
.factory('TokenInterceptor', function($q, $window, $localStorage) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers['X-Access-Token'] = $localStorage.token;
config.headers['X-Key'] = $localStorage.user;
config.headers['Content-Type'] = "application/json";
}
return config || $q.when(config);
},
response: function(response) {
return response || $q.when(response);
}
};
})
app.js
angular.module('starter.controllers', []);
angular.module('starter.services', []);
angular.module('starter.factories', []);
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'starter.factories', 'ngCordova', 'ngRoute'])
.run(function($ionicPlatform, $rootScope, $ionicLoading, $state, $location, $q, $http, $timeout, $localStorage, $window, SessionFactory) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
$ionicPlatform.registerBackButtonAction(function(event) {
if ($state.current.name == "tab.dashboard") {
navigator.app.exitApp();
console.log('1');
} else {
navigator.app.backHistory();
console.log('2');
}
}, 100);
if (window.cordova) {
});
// when the page refreshes, check if the user is already logged in
SessionFactory.check(); $rootScope.showLoading = function(msg) {
$ionicLoading.show({
template: msg || 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
$timeout(function() {
$rootScope.hideLoading();
}, 2999);
}
$rootScope.hideLoading = function() {
$ionicLoading.hide();
};
$rootScope.toast = function(msg) {
$rootScope.showLoading(msg);
$timeout(function() {
$rootScope.hideLoading();
}, 2999);
};
$ionicPlatform.on('resume', function() {
$rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
if ((nextRoute.access && nextRoute.access.requiredLogin) && !SessionFactory.isLogged) {
$location.path("/login");
} else {
// check if user object exists else fetch it. This is incase of a page refresh
if (!SessionFactory.user) SessionFactory.user = $localStorage.user;
if (!SessionFactory.userRole) SessionFactory.userRole = $localStorage.userRole;
}
console.log('true');
});
$rootScope.$on('$routeChangeSuccess', function(event, nextRoute, currentRoute) {
$rootScope.showMenu = SessionFactory.isLogged;
$rootScope.role = SessionFactory.userRole;
// if the user is already logged in, take him to the home page
if (SessionFactory.isLogged == true && $location.path() == '/login') {
$location.path('/tab/price');
}
});
console.log(SessionFactory.isLogged);
$rootScope.$broadcast('onResume');
});
$ionicPlatform.on('pause', function() {
$rootScope.$broadcast('onPause');
console.log('pause');
});
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl',
access: {
requiredLogin: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
login.html
<ion-view view-title="Ionic App">
<ion-content>
<ion-list>
<form name="loginForm">
<div class="list">
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="login.email" required>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="login.password" required>
</label>
<button class="button button-block button-assertive" ng-click="login()" ng-disabled="loginForm.$invalid">
<b>Login</b>
</button>
</div>
</form>
</ion-list>
</ion-content>
</ion-view>
I hope anyone can help me to solve this problem
A Simple and recommended solution : Store user credentials in localStorage and perform auto login. As i see your code, you are already storing some user details in the localStorage. You can check if those details exist in the localStorage when your controller loads and call your login method directly.
Something like this :
function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {
$scope.login = {
email: null,
password: null
};
$scope.isLoggedIn = false;
$scope.login = function() {
// on login set a flag to mark the user as logged in
};
if (!$scope.isLoggedIn) {
if ($localStorage.userName !== undefined and $localStorage.password !== undefined) {
$scope.login();
}
}
]);
Alternatively, if you're working on some login token driven authentication, you can also store that token and use it for communicating with the server next time.
Don't forget to use encryption though (y)
1). In $urlRouterProvider.otherwise(''), set the url of your app's dashboard or main page where user is sent after login. Lets suppose $urlRouterProvider.otherwise('/dashboard').
2). In dashboard's controller, inject the service which checks for user authentication and send the user to login if not authenticated.
It Is Possible By using Local storage In Ionic
Set some credentials in local storage when you logins first time
window.localStorage.setItem("username", "rahul");
window.localStorage.setItem("password", "123");
Check Local storage for credentials when you opens your app next time in .run() method.
var localval = window.localStorage.getItem('username');
var localval1 = window.localStorage.getItem('password');
console.log(localval);
if(localval != null && localval1 != null)
{
$state.go('app.home');
}
Clear apps local storage when you logout from app
window.localStorage.removeItem("username", "rahul");
window.localStorage.removeItem("password", "123");

Angularjs not reloading page with the right json file

I'm storing data and language terms for the website with json, and depending on the language selected i load the adequate file. The problem is when i switch the language, only the adress in the adressbar change without reloading the right json file.
factory.js
app.factory('PostsFactory', function ($http, $q, $timeout) {
var factory = {
posts: false,
find: function (lang) {
var deferred = $q.defer();
if (factory.posts !== false) {
deferred.resolve(factory.posts);
} else {
$http.get(lang+'/json.js').success(function (data, status) {
factory.posts = data;
$timeout(function () {
deferred.resolve(factory.posts);
})
}).error(function (data, status) {
deferred.reject('error')
});
}
return deferred.promise;
},
get: function (id, lang) {
var deferred = $q.defer();
var post = {};
var posts = factory.find(lang).then(function (posts) {
angular.forEach(posts, function (value, key) {
if (value.id == id) {
post = value;
};
});
deferred.resolve(post);
}, function (msg) {
deferred.reject(msg);
})
return deferred.promise;
}
}
return factory;
})
controller
posts.js
app.controller('PostsCtrl', function ($scope, PostsFactory, $rootScope, $routeParams) {
$rootScope.loading = true;
lang = $routeParams.lang;
PostsFactory.find(lang).then(function (posts) {
$rootScope.loading = false;
$scope.posts = posts;
}, function (msg) {
alert(msg);
});
});
post.js
app.controller('PostCtrl', function ($scope, PostsFactory, $routeParams, $rootScope) {
$rootScope.loading = true;
SounanFactory.get($routeParams.id, $routeParams.lang).then(function (post) {
$rootScope.loading = false;
$scope.title = post.title;
$scope.text = post.text;
$scope.image = post.image;
$scope.id = post.id;
}, function (msg) {
alert(msg);
});
});
app.js
var app = angular.module('Posts', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/:lang/', {
templateUrl: 'partials/posts.html', controller: 'PostsCtrl'})
.when('/:lang/post/:id', {
templateUrl: 'partials/post.html', controller: 'PostCtrl'})
.otherwise({
redirectTo: '/en'
});
})
posts.html
<div ng-hide="loading">
<a href="#/en/post/{{post.id}}" ng-repeat="post in posts " class="{{post.class}}">
<div class="title">{{post.title}}</div>
<div class="index">{{post.id}}</div>
</a>
</div>
index.html
<body ng-app="Posts">
<div ng-show="loading">Loading ...</div>
<div class="container" ng-view></div>
<a href="#/fr" >FR</a>
<a href="#/en" >EN</a>
</body>
In your posts.js have you tried adding $scope.$apply() underneath $scope.posts = posts; in posts.js and again under $scope.id = post.id; in post.js?
The problem that you're facing is probably due to Angular's digest cycle and the bizarre way you're trying to pass values around through promises/objects/wizardry.
I mean, it's kind of the least of your worries. I know nothing of the project but there are a few things that could be causing an issue here.
Why do you have a $timeout() without a time?
Why are you setting a lang var and then immediately using it instead of just passing it through?
Why are you assigning a posts member of your factory and then using it immediately instead of just passing it through?
You should be using ng-href for dynamic url's
Let us know how you get on.

Resources