$state.go not working - Error : $state isnot defined - javascript

Hi im Very new Angulay js Ionic development. im trying to basic navigation when button is clicked. but im getting this error when i click the button in Firebug console . i want to navigate to the search page after it clicked
Error : $state isnot defined
Here my App.js Code
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signin', {
url: "/sign-in",
templateUrl: "templates/sign-in.html",
controller: 'AppCtrl'
})
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.search', {
url: "/search",
views: {
'menuContent': {
templateUrl: "templates/search.html"
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/sign-in');
});
here my Controller
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicPopup, $timeout, $ionicModal) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
})
My HTML button is
<button class="button button-block button-positive" id="login-btn" ng-click="signIn(user)" type="submit">Log in</button>

You should also get in the habit of properly injecting your dependencies. It should look like this (including the $state injection):
.controller('AppCtrl',['$scope', '$ionicPopup', '$timeout', '$ionicModal', '$state', function($scope, $ionicPopup, $timeout, $ionicModal, $state) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
}])
Just make sure the order of injections in the quotes are in the same order as the order of your parameters in the following function.

Related

Switch between views based on some condition

I am new to angular and ionic, my app information goes like this: I have a splash screen on which I have my login page,followed by home screen.Now the problem is if the user has logged in once,then whenever the app is closed and opened again it shows the login screen,instead it should show home screen. How do I achieve that. I have tried many solutions, but none of them worked. Kindly help.
var kit = angular.module('starter', ['ionic','ionic.service.core', 'ngCordova']);
kit.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('start', {
url: '/',
templateUrl: 'templates/start.html',
controller: 'StartController'
})
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'HomeController'
})
.state('scrollView', {
url: '/scroll',
templateUrl: 'templates/ScrollEx.html',
controller: 'ScrollExController'
})
.state('check', {
url: '/check',
templateUrl: 'templates/check.html',
controller: 'CheckController'
})
$urlRouterProvider.otherwise('/');
});
In your login page's controller, I assume this is StartController, you can use something like:
// Note you need $location for navigation here:
app.controller('StartController', ['$rootScope', '$scope', '$location', /*...*/
function ($rootScope, $scope, $location /*...*/) {
// Test condition, just an example:
if (sessionStorage.user.id) {
$location.path('/home');
}
// Controller code goes here
});
This is assuming you condition is sessionStorage.user.id.
Angular's $location will handle router navigation elegantly for you.
Source: AngularJS: $location

Angularfire ngRoute/resolve issue, jumps to otherwise

I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work

$on don't catch $broadcast

I have a Angular Project and I want create Authentication mechanism so i have the following controller:
angular.module('authModule')
.controller('LoginCtrl', function($rootScope, $location, loginRESTService, UserService){
var login = this;
function signIn(user) {
loginRESTService.login(user)
.then(function(response) {
console.log(response);
user.access_token = response.user_id;
UserService.setCurrentUser(user);
$rootScope.$broadcast('authorized');
$location.path("/formList");
});
}
})
additional I have a main controller with the following methods
angular.module('authModule')
.controller('MainCtrl', function ($rootScope, $state, LoginService, UserService) {
var main = this;
$rootScope.$on('authorized', function() {
console.log("ENTRE CON PERMISO");
main.currentUser = UserService.getCurrentUser();
});
$rootScope.$on('unauthorized', function() {
console.log("ENTRE SIN PERMISO");
main.currentUser = UserService.setCurrentUser(null);
$state.go('login');
});
})
the problem it's that 'authorized' and 'unauthorized' never was invoked and don't have idea why
my app.js file
angular
.module('pysFormWebApp', [
...
'translateModule',
'formModule',
'authModule'
])
.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/login', {
templateUrl: 'views/auth/login.html',
controller: 'LoginCtrl',
controllerAs: 'login'
})
.otherwise({
redirectTo: '/'
});
my index.html (only a part because is so long and is the index that generate yo angular)
<div ng-controller="MainCtrl as main" >
<button ng-if="main.currentUser" class="btn btn-default navbar-btn" ng-click="main.logout()">Logout <strong>{{main.currentUser.name}}</strong>
</button>
</div>
First, you are not broadcasting the 'unauthorized' event. because of that the $rootScope.on('unauthorized') is not working.
Second. Maybe are running the main controller before the login controller, and because of that your controller doesn't catch the event.
let me know if it solves your problem.

How to load login page as first page

I am using ionic framework. I am trying to load login page as first page but cant see its just getting an empty page.
My code looks like
app.js:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
and controller:
.controller('AppCtrl', function ($scope, $state, $ionicModal) {
$ionicModal.fromTemplateUrl('templates/login.html', function(modal) {
$scope.loginModal = modal;
},
{
scope: $scope,
animation: 'slide-in-up',
focusFirstInput: true
}
);
//Be sure to cleanup the modal by removing it from the DOM
$scope.$on('$destroy', function() {
$scope.loginModal.remove();
});
.controller('LoginCtrl', function ($scope, $state, AuthenticationService) {
$scope.message = "";
$scope.user = {
username: null,
password: null
};
$scope.login = function () {
AuthenticationService.login($scope.user);
};
$scope.$on('event:auth-loginRequired', function (e, rejection) {
console.log('handling login required');
$scope.loginModal.show();
});
$scope.$on('event:auth-loginConfirmed', function () {
$scope.username = null;
$scope.password = null;
$scope.loginModal.hide();
});
But still cant see it.
my app looks like
https://github.com/keithdmoore/ionic-http-auth but without the home page.
Thnx!
try to change your app.config section.
app.config(function ($stateProvider) {
$stateProvider.otherwise({ redirectTo: '/login' });
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
}).state('login', {
url: "/login",
templateUrl: "login.html page url",
controller: 'login controller'
}));
don't need to write any code appcontroller'. Whenever you run the application the url path is should be empty. So this line $stateProvider.otherwise({ redirectTo: '/login' }); helps to open the login screen.

How to access URL parameters in named views using ui-router

I am clicking on an anchor tag boofing and trying to access the URL parameters values into my app.js but I am getting null values for $scope, $stateParam, $state.
app.js
...
.state('bar', {
url: '/boof?sid&qid',
views: {
'': {
templateUrl: 'partials/a.html',
controller: function ($scope, $stateParams, $state) {
//not getting $scope, $stateParams, $state
}
},
'foo#bar': {
templateUrl: 'partials/b.html',
controller: function ($scope, $stateParams, $state) {
//not getting $scope, $stateParams, $state
}
},
...
}
})
...
a.html
<div ui-view="foo"></div>
<div ui-view="xyz"></div>
b.html
<div>
//stuff using data from $scope, $stateParams, $state
</div>
Could somebody help me understand why am I getting null values for $scope, $stateParams, $state.
Also, could I just do a controller: 'myController' as below and access the $stateParams, $state in myController?
app.js
...
.state('bar', {
url: '/boof?sid&qid',
views: {
'': {
templateUrl: 'partials/a.html',
controller: 'myController'
}
},
'foo#bar': {
templateUrl: 'partials/b.html',
controller: 'myController'
}
},
...
}
})
...
myApp.controller("myController", ['$scope', '$http', '$stateParams', '$state', function($scope, $http, $stateParams, $state){
//accessing $stateParams and $state here
} ]);
I tried to do it, but I was getting a null value for both $stateParams and $state.

Categories

Resources