$state.go on onEnter function of an abstract state - angularjs

I have the following UI Router configuration witch includes a login page (/login), an abstract page that will be the parent of all my admin pages (/admin) and a list page that extends from the abstract page (/admin/list):
$stateProvider
.state('login', {
url: '/login',
templateUrl: '/pub/login.html',
controller: 'LoginController',
controllerAs: '$loginCtrl',
onEnter: function () {
console.log("enter /login");
}
})
.state('admin', {
abstract: true,
url: '/admin',
templateUrl: '/tmpl/templateAdmin.html',
onEnter: function () {
console.log("enter admin abstract");
// Validate JWT here and if not authenticated forward to login
$state.go('login');
}
})
.state('admin.list', {
url: '/list',
templateUrl: '/prv/clientsList.html', // loaded into ui-view of parent's template
controller: 'AppController',
controllerAs: '$appCtrl',
onEnter: function () {
console.log("enter admin/list");
}
})
I want to implement a logic that will validate if the user is authenticated when accessing an /admin/* page. In order to do that I added an onEnter function in my abstract state so that I could use $state.go('login'). But this doesn't work. How can I do this? Is there a better way to validate authentication inside UI Router?

In this case, I think it's better if you used resolve instead of onEnter.
Mainly because you want to check if the user is authenticated before navigation. If the objects inside the block don't resolve then the controller passed to the state won't be instantiated.
.state('admin', {
abstract: true,
url: '/admin',
templateUrl: '/tmpl/templateAdmin.html',
resolve: {
currentUser: function (authService) {
return authService.getUser();
}
}
}
The root state would try and resolve the user for all child views nested inside.
Here's the link to the docs on Nested States and Inherited Resolved Dependencies:
https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views

Related

Angularjs ui-router login model example

I'm new to angularjs and bootstrap and I'm recently working on a web app which requires 2 different set of views (public and private).
For the public view, everyone can see it and it has it's own top menu navbar and the corresponding content.
For the private view, only authenticated users are able to see. The private view should have a totally different top menu and its corresponding content. (Maybe a side menu navbar but this is off topic).
I've read the api page for ui-router from here. And I've implemented the navigation like this. (plunker)
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('public', {
'abstract': true,
views: {
'mainView#': {
templateUrl: 'public.html'
}
}
})
.state('home', {
parent: 'public',
url: '/',
templateUrl: 'home.html'
})
.state('login', {
parent: 'public',
url: '/login',
templateUrl: 'login.html',
controller: 'LoginController'
})
.state('private', {
'abstract': true,
views: {
'mainView#': {
templateUrl: 'private.html'
}
}
})
.state('dashboard', {
parent: 'private',
url: '/dashboard',
templateUrl: 'dashboard.html'
})
.state('settings', {
parent: 'private',
url: '/settings',
templateUrl: 'settings.html'
})
.state('logout', {
parent: 'private',
url: '/logout',
templateUrl: 'logout.html',
controller: 'LogoutController'
})
});
The example plunker I had above is working, but I'm not sure this is the "best" approach for handling such navigation. I'd very appreciate if someone can help me enhancing my solution.
Thanks in advance.
I like your approach and it looks clean. However, one thing I see it lacking is security. You can quickly add security by adding a resolve dependency.
Resolve
You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.
The resolve property is a map object. The map object contains key/value pairs of:
key – {string}: a name of a dependency to be injected into the controller.
factory - {string|function}:
If string, then it is an alias for a service.
Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before the controller is instantiated and its value is injected into the controller.
.state('dashboard', {
parent: 'private',
url: '/dashboard',
templateUrl: 'dashboard.html',
resolve:{
promiseObj: function($http){
// $http returns a promise for the url data
// returns a promise so the resolve waits for it to complete
// If the promise is rejected, it will throw a $stateChangeError
return $http({method: 'GET', url: '/someUrl'}); // confirm here that the user is logged in
}
})

AngularJS: Is it possible to ignore parent's state url while using UI-Router?

I'm developing an AngularJs application using UI-Router(-extras) in which I use the following setup:
.state('root', {
url: '/{language:(?:nl|en)}',
views: {
'root': {
templateUrl: 'app/root/root.html',
controller: 'RootController'
}
}
})
.state('root.main', {
views: {
'main': {
templateUrl: 'app/main/main.html',
controller: 'MainController'
}
},
sticky: true
})
.state('root.modal', {
url: '/{locale:(?:nl|fr)}',
views: {
'modal': {
templateUrl: 'app/modal/modal.html',
controller: 'ModalController'
}
}
})
The root state defines the language in the URL. Furthermore I have several modal and main states which have their own URL (i.e. root.main.home => /en/home).
Now I want to have some modal states that have no URL. How can I make a state ignore his parent's URL?
To answer:
how can a state ignore his parent's URL?
we have
Absolute Routes (^)
If you want to have absolute url matching, then you need to prefix your url string with a special symbol '^'.
$stateProvider
.state('contacts', {
url: '/contacts',
...
})
.state('contacts.list', {
url: '^/list',
...
});
So the routes would become:
'contacts' state matches "/contacts"
'contacts.list' state matches "/list". The urls were not combined because ^ was used.
Also check this: how to implement custom routes in angular.js?

Angular ui-router... Display default tab

I am arriving on bookDetails state form some other link. Here bookDetails state's template has links for different tabs (or templates). And associated controller EditBookController has a json file using which I am building forms in different tabs with states like bookDetails.basic and bookDetails.publisher which use parent EditBookController. It's working fine. How to directly display the default bookDetails.basic instead of making user click the link? If I make bookDetails abstract(abbstract:true) and provide an empty link to bookDetails.basic I get following error Cannot transition to abstract state 'bookDetails'
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url:'/home',
controller: 'HomeController',
templateUrl: '/static/publisher/views/Publisher_Home_Template.html'
})
.state('books', {
url:'/books',
controller: 'BooksController',
templateUrl: '/static/publisher/views/Book_Listing_Template.html'
})
.state('bookDetails', {
url : '/books/:b_id',
controller: 'EditBookController',
templateUrl: '/static/publisher/views/Product_Page_Template.html'
})
.state('bookDetails.basic', {
url : '/basic',
templateUrl: '/static/publisher/views/tab1.html'
})
.state('bookDetails.publisher', {
url : '/publisher',
templateUrl: '/static/publisher/views/tab2.html'
})
A plunk with similar problem. but code is different On clicking form it should land on the profile profile form.
I created working example here
There is similar question: Redirect a state to default substate with UI-Router in AngularJS
The solution comes from a cool "comment" related to an issue with redirection using .when() (https://stackoverflow.com/a/27131114/1679310) and really cool solution for it (by Chris T, but the original post was by yahyaKacem)
https://github.com/angular-ui/ui-router/issues/1584#issuecomment-75137373
In the state definition I added ONLY one setting to bookDetails state, the: redirectTo: 'bookDetails.basic',. Let's have a look:
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url:'/home',
controller: 'HomeController',
templateUrl: '/static/publisher/views/Publisher_Home_Template.html'
})
.state('books', {
url:'/books',
controller: 'BooksController',
templateUrl: '/static/publisher/views/Book_Listing_Template.html'
})
.state('bookDetails', {
// NEW LINE
redirectTo: 'bookDetails.basic',
url : '/books/:b_id',
controller: 'EditBookController',
templateUrl: 'static/publisher/views/Product_Page_Template.html'
})
.state('bookDetails.basic', {
url : '/basic',
templateUrl: '/static/publisher/views/tab1.html'
})
.state('bookDetails.publisher', {
url : '/publisher',
templateUrl: '/static/publisher/views/tab2.html'
})
And now - only these few lines will do the miracle:
app.run(['$rootScope', '$state',
function($rootScope, $state) {
$rootScope.$on('$stateChangeStart',
function(evt, to, params) {
if (to.redirectTo) {
evt.preventDefault();
$state.go(to.redirectTo, params)
}
}
);
}]);
This way we can adjust any of our states with its default redirection...Check it here
From Directing the user to a child state when they are transitioning to its parent state using UI-Router:
Either change the bookDetails.basic state to:
.state('bookDetails.basic', {
url : '',
templateUrl: '/static/publisher/views/tab1.html'
})
Or add the following routing:
$urlRouterProvider.when('/books/{b_id}', '/books/{b_id}/basic');
Try to add $state.go('bookDetails.basic') inside EditBookController. If I understood you< this will help.

undefined stateParams using ui-router

Question: For some reason I can't get my controller to recognize my url parameters across sessions.
Background: I have a nested view called modal that takes a parameter, whose url is /modal/:id (eg: /#/modal/1/ or /#/floorplan/1+2/). Ideally, when the user goes to this url, a modal will automatically open with the resource(s) with the given id.
Since the parent state and the child state(modal) are being handled by the same controller, the modal state has a custom data attribute (modalStatus) in its configuration set to true. When this custom attribute is enabled the modal is displayed.
I can currently go from the parent state to the nested state and trigger the modal but when I start a new session or refresh the page with a url like /modal/3, the application fails to read the parameters ($stateParams), which is being logged as an empty object.
I have tried using onEnter and Resolve but I'm not exactly clear on how to use them in this scenario.
Router
$stateProvider
.state('home', {
name: 'home',
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.state('home.modal', {
url: 'modal/:id/',
data: {
modalState: true
},
controller: 'MainCtrl'
})
Relevant part of controller:
$scope.init = function() {
console.log($stateParams);
if ($state.current.data) {
if ($state.current.data.modalState === true) {
$scope.openModal();
}
}
};
$scope.init();
edit: plunkr
You could try adding the params option:
$stateProvider
.state('home', {
name: 'home',
params: {
id: null
},
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.state('home.modal', {
url: 'modal/:id/',
data: {
modalState: true
},
controller: 'MainCtrl'
});
The child state home.modal should inherit the params of the parent. On your ui-sref from one state to another, pass the param like so:
<a ui-sref="home.modal({ id: x })"></a>
Then your url would turn out to be /modal/:x (where x is the number).
Also the $stateParams should then show the params as you wished.

How to access data from my controller in a state

What is the best way to stop a user from going to a state if there is no data for that state? I need to redirect the user to /featured if there is no data in one of the other states.
I thought that I could check the controller for data first and then redirect using $state.go if the data was null, but I can't find an example of how to access data in a controller inside of an onEnter event
I think a code example should sum it up:
fseControllers.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/featured");
$stateProvider
.state('featured', {
url: "/featured",
templateUrl: "featured-template"
})
.state('friends', {
url: "/friends",
templateUrl: "friends-template",
controller: 'FseController',
onEnter: function(){
// Here I want to redirect to /featured if no data in controller
}
})
.state('stories', {
url: "/stories",
templateUrl: "stories-template"
})
.state('events', {
url: "/events",
templateUrl: "events-template"
})
})
You could refactor your controller to use a service , that can be injected into onEnter function and to the Controller.
AngularJS Services
onEnter:function(FriendsService, $location){
if(!!FriendsService.getFriends()){
$location.path("/featured");
}
}

Resources