$state.go() is not refreshing my ionic page - angularjs

I have tried several method but $state.go() is not refreshing my page.Here is my controller. All process works but i cannot reload the browse page using $state.go() function.
angular.module('kawaadi.controllers', [])
.controller('AppCtrl', function ($scope, Service, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $state, $http,$location) {
$scope.loginData = {};
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function (modal) {
$scope.modal = modal;
});
$scope.closeLogin = function () {
$scope.modal.hide();
};
$scope.login = function () {
$scope.modal.show();
};
$scope.logout = function () {
localStorage.setItem("token", "");
$state.go('login');
};
$scope.statusData = function (pid, uid, status) {
$ionicLoading.show({
template: 'Processing...'
});
Service.change_status(pid, uid, status, $http).success(function (data) {
if (data.status === 'success' && data.notification_status === 'success') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed and notification has been send!'
});
} else if (data.status === 'success' && data.notification_status === 'failure') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed but failed to send notification!!'
});
}
alertPopup.then(function (res) {
if (res == true) {
$state.go('app.browse');
}
});
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Process failed!',
template: 'Some thing went wrong!'
});
});
}
})
and here is my url router
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/auth.html',
controller: 'LoginCtrl'
})
.state('app', {
url: '/app',
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html',
controller: 'pickupCtrl'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
});
Please guide me. Thanks in advance

Please modify all your states as
.state('emailConfirmation',{
cache: false,
url:"/emailConfirmation",
templateUrl:"app/session/emailConfirmation.html",
controller: 'EmailConfirmationCtrl'
})
and to reload the current page please use these command
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});

If you want to force reload the current state, then you probably need to use $state.go($state.current.name, $state.params, {reload: true}) as mentioned here

Just Add the following in Your ion-view tag
<ion-view cache-view="false">

Related

Unable to access a public state in angular project?

in my web app am using angular-ui-router for state change. Below is my route.config file.
route-config.js
$stateProvider
.state('login', {
url: '/',
views:{
pageContent:{
templateUrl: 'Login/login_default.html',
controller: 'loginController'
},
footer:{
templateUrl: 'common/footer.html',
controller: 'footerController'
}
},onEnter: function(){
// if(true){ $state.go('dashboard')}
},resolve:{
dependencies:['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['ui.bootstrap','ngMessages','headerCtrl','footerCtrl']);
}],
loginController:['$q', '$ocLazyLoad','dependencies',function($q, $ocLazyLoad,dependencies) {
var deferred = $q.defer();
require.ensure(['./styles/login/login.less'], function (require) {
var mod = require('./Login');
$ocLazyLoad.load({
name: mod.name,
});
deferred.resolve(mod.controller);
});
return deferred.promise;
}]
},public:true
})
.state('Password', {
url: '/Password?token',
views:{
header:{
templateUrl: 'common/header.html',
controller:"headerController"
},
pageContent:{
templateUrl: 'ForgotPassword/forgotPassword.html',
controller: 'forgotPasswordCtrl'
},
footer:{
templateUrl: 'common/innerFooter.html',
controller: 'footerController'
}
},
resolve:{
dependencies:['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['headerCtrl','ui.bootstrap']);
}],
forgotPasswordCtrl:['$q','$ocLazyLoad','dependencies', function($q,$ocLazyLoad,dependencies) {
var deferred = $q.defer();
require.ensure(['./styles/forgotPassword/forgotPassword.less'], function (require) {
var mod = require('./ForgotPassword');
$ocLazyLoad.load({
name: mod.name,
});
deferred.resolve(mod.controller);
});
return deferred.promise;
}]
},public:true
});
In index.js file am checking the $stateChange as below.
run(function($http,$rootScope,$cookieStore,$location,$window,$state) {
$rootScope.token = $http.defaults.headers.common['SessionID'];
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
let loggedIn = $cookieStore.get('success');
if(!toState.public && !loggedIn){
$state.go('login');
event.preventDefault();
}
});
});
And below is the Html page on which on click on password button it should go to forgot password page or if i will type password on the URL it should go to the password page.
<div class="inp-wrapper frgtpwd">
<a style="text-decoration:none;color:#000;" ui-sref="Password" class="password">FORGOT PASSWORD ?</a>
</div>
I tried everything but unable to fix this issue. If i will check the toState.name in $statechangeStart function and try to go to the password page then it is going under a continuous loop and throwing error like Maximum call stack(something like this).

error while calling to $modal service from run block

In my main module i have used ui-bootstrap modal for checking login authentication.From run block i have called to loginModal service but it is giving Error
TypeError: loginModal is not a function
angular.module('myApp', ['ui.router', 'ui.bootstrap', 'loginServices','leaveServices']). config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider.
state('home', {
url:'/home',
data: {
requireLogin: false
},
views: {
'': {
templateUrl: 'partials/templates/assets/home.html'
}
}
}).
state('home.about', {
url: '/about',
templateUrl: 'partials/templates/assets/about.html'
}).
state('home.contact', {
url: '/contact',
templateUrl: 'partials/templates/assets/contactUs.html'
}).
state('/login', {
url: '/login',
data: {
requireLogin: false
},
templateUrl: 'partials/login.html',
controller: loginUserController
}).
state('/register', {
url:'/register',
data: {
requireLogin: false
},
templateUrl: 'partials/registerUser.html',
controller: registerController
}).
state('/getAllUsers', {
url: '/getAllUsers',
data: {
requireLogin: false
},
templateUrl: 'partials/getAllUsers.html',
controller: getUsersController
}).
state('/updateUser', {
url : '/updateUser/:id/:name',
data: {
requireLogin: true
},
params: {'id':null, 'name':null},
templateUrl: 'partials/updateUser.html',
controller: updateUserController
}).
state('/userLeave', {
url : '/userLeave:name',
data: {
requireLogin: true
},
params: {'name': null},
templateUrl: 'partials/userLeave.html',
controller: userLeaveController
}).
state('/leaveRequest', {
url : '/leaveRequest',
data: {
requireLogin: true
},
templateUrl: 'partials/leaveRequest.html'
});
}])
.run(function ($rootScope, $state, loginModal) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
console.log('going to state '+toState.name);
if (requireLogin && typeof $rootScope.currentUser === 'undefined') {
event.preventDefault();
loginModal().then(function () {
return $state.go(toState.name, toParams);
})
.catch(function () {
return $state.go('/login');
});
}
});
})
.factory('loginModal', function ($modal, $rootScope) {
function assignCurrentUser (user) {
$rootScope.currentUser = user;
return user;
}
return function() {
var instance = $modal.open({
templateUrl: 'partials/login.html',
controller: loginUserController
});
return instance.result.then(assignCurrentUser);
}
});
here login controller
loginUserController.$inject = ['$scope','$http', 'loginFactory', '$location', '$state'];
function loginUserController($scope,$http,loginFactory,$location, $state){
$scope.validateLogin = function(name,password){
$http.get("http://localhost:3010/validateLogin?userName="+name+"&password="+password)
.then(function(response) {
if(response.data.length != 0) {
console.log("logged user data is "+JSON.stringify(response.data));
$state.transitionTo('/userLeave', {name: name});
// $scope.$close(response);
}
else
$scope.inValidUser = 'Invalid User';
});
};
$scope.cancel = $scope.$dismiss;
}
Could be because you're using an Angular service which expects a constructor which in turn, should not be returning something.
Try changing to a factory, eg
.factory('loginModal', ...

Angularjs $location.path('...') doesn't work

I'm working on authentication with angularjs, so after connecting my user I want to redirect him to the home page:
$scope.submit = function(user) {
var request = {
method: 'POST',
url: 'http://localhost:9001/signIn',
headers: {
'Content-Type': 'application/json'
},
data: {
"email": user.email,
"password": user.password,
"rememberMe": true
}
};
$http(request).then(function(data) {
$location.path('/home');
}, function(error) {
console.log(error);
});
};
here is my configuration:
app.config(function($urlRouterProvider, $stateProvider, $httpProvider, $authProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
.state('signIn', {
url: '/signIn',
templateUrl: '/signIn',
controller: 'SignInCtrl'
});
});
I tried this:
$http(request).then(function(data) {
$scope.$evalAsync(function() {
$location.path('/home');
});
console.log(data);
}, function(error) {
console.log(error);
});
also :
$location.path('/home');
$location.replace();
Neither of the above work, any help is greatly appreciated.
The home state resolver function fails to resolve or reject the $q.defer promise when $auth.isAuthenticated() returns false. This will cause the promise to hang and create a memory leak.
//ERRONEOUS CODE
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
//FAILS to resolve or reject promise
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
Instead return a rejection when not authenticated:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
//var deferred = $q.defer();
if ($auth.isAuthenticated()) {
return $q.resolve("AUTHENTICATED");
};
//otherwise
return $q.reject("NOT AUTHENTICATED");
})
}
})
When a resolver function returns a rejected promise, the state change will be prevented and the $stateChangeError event will be broadcast on $rootScope.

Did I miss anything with this $http.jsonp in angularjs?

I know this question has been asked several times, but I'm not understanding if I missed anything or it's just a server thing.
I need to show you my code for checking please:
(function(){
var app = angular.module('c4s', ['ionic', 'starter.controllers', 'starter.services']);
app.controller('curiousCtrl', function($http, $scope){
$scope.stories = [];
$http.jsonp('http://curious4science.com/?json=1&callback=JSON_CALLBACK')
.success(function(response) {
angular.forEach(response.data.children, function(child){
console.log(response);
$scope.stories.push(child.data);
});
});
});
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
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();
}
});
})
.config(function($httpProvider, $stateProvider, $urlRouterProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
}());
And I'm getting this error:
TypeError: response.data is undefined
First, I tried $http.get(....) but I got the error that cross domain thing is not allowed. Then I tried jsop.
Thank you.
The sucess() callback doesn't take the http response as argument. It takes the response data, then the status, then the headers, then the config.
So the code should be
$http.jsonp('http://curious4science.com/?json=1&callback=JSON_CALLBACK')
.success(function(data) {
angular.forEach(data.children, function(child){
console.log(response);
$scope.stories.push(child.data);
});
});
(assuming the returned JSON has a children field which is an array, and that each child has a data field, of course).

AngularJS UI-router stateprovider issue

Im currently using Ionic and was playing with a app with tabs. (I.e has a bottom bar with icons).
Right now I want to remove it but ended messing up the routing. The devtools does not show any errors. I cannot transit from login page to main "posts" page. On login, clicking the login button does do anything. I have edited the state.go('') in the controllers accordingly.
Ill show before and after the changes.
Would it make sense to remove views :{} totally? I find it complicates things and I do not use nested views. Not sure if modal page requires views.
Appreciate some help/ advice on how to get around the error.
Before
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// --------Authenticate states ----------------
.state('auth', {
url: '/auth',
templateUrl: 'templates/auth.html',
controller: 'StartCtrl'
})
.state('register', {
url: '/register',
templateUrl: 'templates/register.html',
controller: 'AuthCtrl',
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'AuthCtrl',
})
// ---------- Main states ---------------------
.state('tab.posts', {
url: '/posts',
views: {
'tab-posts': {
templateUrl: 'templates/tab-posts.html',
controller: 'PostsCtrl'
}
}
})
.state('tab.newpost', {
url: '/newpost',
views: {
'tab-posts': {
templateUrl: 'templates/tab-newpost.html',
controller: 'NavCtrl'
}
}
})
.state('tab.posts.view', {
url: '/posts/:postId',
views: {
'tab-posts#tab': {
templateUrl: 'templates/tab-showpost.html',
controller: 'PostViewCtrl'
}
}
})
.state('tab.profile', {
url: '/users/:userId',
views: {
'tab-posts': {
templateUrl: 'templates/tab-profile.html',
controller: 'ProfileCtrl',
}
}
})
After
.state('/', {
url: '/',
abstract: true,
templateUrl: 'templates/tab-posts.html'
})
// --------Authenticate states ----------------
.state('auth', {
url: '/auth',
templateUrl: 'templates/auth.html',
controller: 'StartCtrl'
})
.state('register', {
url: '/register',
templateUrl: 'templates/register.html',
controller: 'AuthCtrl',
resolve: {
user: function(Auth){
return Auth.resolveUser();
}
}
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'AuthCtrl',
resolve: {
user: function(Auth){
return Auth.resolveUser();
}
}
})
//----------- Main states--------------------
.state('posts', {
url: '/posts',
views: {
'posts': {
templateUrl: 'templates/tab-posts.html',
controller: 'PostsCtrl'
}
}
})
.state('newpost', {
url: '/newpost',
views: {
'posts': {
templateUrl: 'templates/tab-newpost.html',
controller: 'NavCtrl'
}
}
})
.state('posts.view', {
url: '/posts/:postId',
views: {
'posts#': {
templateUrl: 'templates/tab-showpost.html',
controller: 'PostViewCtrl'
}
}
})
.state('profile', {
url: '/users/:userId',
views: {
'posts': {
templateUrl: 'templates/tab-profile.html',
controller: 'ProfileCtrl',
}
}
});
Updated for Levi
app.factory('Auth', function($firebase, $firebaseAuth, FIREBASE_URL, $rootScope) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseAuth(ref);
var Auth = {
register: function (user) {
return auth.$createUser(user.email, user.password);
},
login: function (user) {
return auth.$authWithPassword(user);
},
logout: function() {
auth.$unauth();
},
resolveUser: function() {
return auth.$waitForAuth();
},
signedIn: function() {
return !!Auth.user.provider;
},
createProfile: function (user) {
var profile = {
username: user.username,
md5_hash: user.md5_hash
};
var profileRef = $firebase(ref.child('profile'));
return profileRef.$set(user.uid, profile);
},
user: {}
};
auth.$onAuth(function (user){
if(user) {
angular.copy(user, Auth.user);
Auth.user.profile = $firebase(ref.child('profile').child(Auth.user.uid)).$asObject();
console.log(Auth.user);
} else {
console.log('logged out');
if (Auth.user && Auth.user.profile) {
Auth.user.profile.$destroy();
}
angular.copy({}, Auth.user);
}
});
return Auth;
});
Image for error trace
Remove you resolver from your login state.
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'AuthCtrl',
})
If a someone want to go to login, you can't force him to be logged in.

Resources