Using $state.go() with onResume() - javascript

I am trying to redirect to my login page each time my application comes from background to foreground but I get that error :
Uncaught TypeError: $state.go is not a function
So I obviously did something wrong, but I can't get what.
Here is some parts of my code in my app.js :
// Ionic Starter App
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('resetLogin', {
url: '/resetLogin',
templateUrl: 'templates/resetLogin.html',
controller: 'ResetLoginCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
$urlRouterProvider.otherwise('/login');
})
.run(function($ionicPlatform, $state) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
function onDeviceReady() {
}
});
document.addEventListener("resume", onResume, false);
function onResume($state){
$state.go('login');
}

Juste move your function in the block run and remove $state in the onResume.
Only angular function are injectable. In fact you're probably getting an event object in your case but surely not the $state.
.run(function($ionicPlatform, $state) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
function onDeviceReady() {
}
document.addEventListener("resume", onResume, false);
function onResume(){
$state.go('login');
}
});

Related

Adding hardware Back button to Home for Ionic in android

Ionic has a different navigation when press a function from side menu. When you press a back button from handset, it will straight away exit.
I refer to this tutorial and make the changes to my app.js but it unable to back to home page but exit the app.
The code suppose to (which is what I needed):
1.if not at home page, it will back to previous page if press hardware back button
2.if it is at home page, press hardware back button will show pop up to confirm if user really want to exit.
app.js
angular.module('myapp', ['ionic', 'myapp.controllers', 'myapp.factories'])
.run(function($ionicPlatform,$state,$ionicHistory,$ionicPopup) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
if ($state.current.name == "app.home") {
var confirmPopup = $ionicPopup.confirm({
title: 'Exit',
template: 'Confirm Exit'
});
confirmPopup.then(function (res) {
if (res) {
navigator.app.exitApp();
}
});
} else {
$ionicHistory.nextViewOptions({ disableBack: true });
$state.go('app.home');
}
}, 100);//registerBackButton
});
})
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'menuCtrl'
})
.state('app.home', {
url: '/home',
views: {
'menuContent': {
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
}
}
})
.state('app.personalitem', {
url: '/personalitem',
views: {
'menuContent': {
templateUrl: 'templates/personalitem.html',
controller: 'personalitemCtrl'
}
}
})
.state('app.pStock', {
url: '/pStock',
views: {
'menuContent': {
templateUrl: 'templates/pStock.html',
controller: 'pStockCtrl'
}
}
});
angular.module('myapp.factories', []);
angular.module('myapp.controllers', []);
How shall I do with my code so that I can get the hardware back button work?
Can you try:
menu.ts openPage(page) {
this.nav.setRoot(page.component);
}
menu.html <button class="menuList" menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
{{p.title}}
</button>
app.component.ts pages: any[] = [
{ title: 'Welcome', component: IntroPage },
{ title: 'Home', component: TabsPage },
]

How to angularjs pagination using $http

I am trying to create a pagination using Angularjs in Ionic Framework. Please help me to write code of pagination. I am getting data form this json url.
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
$scope.data = response.data;
});
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
});
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function($ionicPlatform) {
$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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
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'
}
}
})
.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'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
});
playlists.html
<ion-view view-title="Playlists">
<ion-content>
<ion-list>
<ion-item ng-repeat="playlist in data | firstPage:currentPage*pageSize | limitTo:pageSize" href="#/app/playlists/{{playlist.id}}">
{{playlist.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
<< 1/2/3/4/5 >>
You need to set pageSize to the total number of movies returned as the response does not contain any meta data about the response:
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
// populate data with the array of movies
$scope.data = response.data;
// set the page size to the total number of movies
$scope.pageSize = $scope.data.length;
});
});

Ionic view name not working

I have an ionic app that I'm trying to build some views for. However, for some reason when I create a unique view-name name, my view doesn't work and it redirects to #/tab/home. The view I'm trying to create is called login, it should be accessed by going to #/tab/login.
Here's my full app.js file.
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ui.rCalendar'])
.run(function($ionicPlatform) {
$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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// 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('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl'
}
}
})
.state('tab.feed', {
url: '/feed',
views: {
'tab-feed': {
templateUrl: 'templates/tab-feed.html',
controller: 'FeedCtrl'
}
}
})
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
.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.events', {
url: '/events',
views: {
'tab-events': {
templateUrl: 'templates/tab-events.html',
controller: 'EventsCtrl'
}
}
})
.state('tab.cart', {
url: '/cart',
views: {
'tab-cart': {
templateUrl: 'templates/tab-cart.html',
controller: 'CartCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/login');
});
I've got a file called tab-login.html. When I change the view-name from tab-login to anything else that already exists like tab-feed, when I go to #/tab/login it works fine. So it works when it looks like this:
.state('tab.login', {
url: '/login',
views: {
'tab-feed': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
It works just fine...which makes no sense to me. What am I doing wrong? And why is it redirecting to home when I have it set to default to login?

ui-router - $state.go() not working

Here is the app.js of my project:
(function () {
'use strict';
angular
.module('app', ['ui.router', 'ngCookies', 'angular-inview', 'ngMaterial'])
.config(config)
.run(run);
config.$inject = ['$stateProvider', '$urlRouterProvider', '$mdThemingProvider'];
function config($stateProvider, $urlRouterProvider, $mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('deep-orange')
.accentPalette('teal', {
'default': 'A400'
});
$urlRouterProvider.otherwise('/app');
$stateProvider
.state('app', {
url: '/app',
data: {
clearenceLevel: 1
},
views: {
'': {
templateUrl: 'app/views/navbar.html',
}
}
})
.state('home.works', {
url: '/works',
templateUrl: 'app/views/works.html',
controller: 'WorksController as vm'
})
.state('login', {
url: '/login',
templateUrl: 'app/views/login.html',
controller: 'LoginController as vm',
data: {
clearenceLevel: 0
}
})
.state('register', {
url: '/register',
templateUrl: 'app/views/register.html',
controller: 'RegisterController as vm',
data: {
clearenceLevel: 0
}
});
}
run.$inject = ['$rootScope', '$location', '$state', '$cookieStore', '$http', 'AuthenticationService'];
function run($rootScope, $location, $state, $cookieStore, $http, AuthenticationService) {
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['aimm-token'] = $rootScope.globals.currentUser.token;
$http.defaults.headers.common['aimm-id'] = $rootScope.globals.currentUser.id;
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var clearenceLevel = toState.data.clearenceLevel;
var loggedIn = $rootScope.globals.currentUser;
if (clearenceLevel > 0 && !loggedIn) {
alert("redirecting");
return $state.go('login');
}
});
}
})();
I just can't have $state.go() working. The $on('$stateChangeStart'...); is working fine, and the alert is poping when trying to reach a protected state with no session. But the return $state.go('login'); doesnt work. It redirects to /app.
Thanks for your help.
Well, thanks to #Vanojx1, I found out adding e.preventDefault(); before the $state.go('login'); made it work. Still dont understand why though.
You need to execute the $state.go on main scope and not in a (angular) service or virtual scope created temporarily.
You can also solve the problem by wrapping it in $timeout or setTimeout which will register it in the browser loop to be executed after the current method run etc even with 0 milliseconds will do it, like.
$timeout(()=>{$state.go('xyz')},0)
or
setTimeout(()=>{$state.go('xyz')},0);

Ionic/Angular $urlRouterProvider.otherwise issue

I am having issues with Ionic/Angular. I am new to ionic, and need some help. Most of the stuff online is for splash screens, so I came here for further assistance.
I want the app to default land on to the "welcome" page. What do I need to write? My code is as follows.
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function($ionicPlatform) {
$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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.welcome', {
url: "/welcome",
views: {
'menuContent': {
templateUrl: "templates/welcome.html"
}
}
})
.state('app.bulletin', {
url: "/bulletin",
views: {
'menuContent': {
templateUrl: "templates/bulletin.html"
}
}
})
.state('app.lunch', {
url: "/lunch",
views: {
'menuContent': {
templateUrl: "templates/lunch.html"
}
}
})
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise("/app/welcome");
});
I think you need to remove the }); above the $urlRouterProvider since you have to define the otherwise() inside of the config;
app.config(function($urlRouterProvider){
// if the path doesn't match any of the urls you configured
// otherwise will take care of routing the user to the specified url
$urlRouterProvider.otherwise('/index');
})

Categories

Resources