Angular routing based on a condition - angularjs

I have been trying to find a way to implement angular routing which routes based on a condition rather than which link the user clicks
route1 -> view1
route2 -> view2
To add complication, the condition itself is evaluated on the result of a service. I am retrieving a set of items for my shopping cart checkout app. I need the shopping cart to route to view1 if the number of items is > 0. And a different route if it is 0.
if (itemListService.getItems().length > 0) --> route1
else --> route2
And because of this, the complication which arises is that the routing has to wait until the service result is evaluated before loading the corresponding view. In other words, the promise of the service has to be resolved.
I found the following post where someone suggested using 'resolve' configuration property within the routeprovider, but that only solves the issue of waiting for the service response. I'm not sure if it satisfies checking a condition based on the service response.
Redirecting to a certain route based on condition
Can someone help me with this?
Would ui-router be able to implement this better than routeProvider?

Yes,It can be easily done using ui-router.For example,create four states: the dashboard state,which links you to the resolver state.On entering your resolver state based on your service's data you can redirect to appropriate state.This is done with the help of OnEnter hook of the resolver state.
Demo Plunker
In the plunker,
Click on parent in dashboard
It will navigate to state child1 until the items in service has values
When all the items is popped out it will navigate to state child2
Code:
var myapp = angular.module('myapp', ["ui.router"]);
myapp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/dashboard")
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html'
}).state('parent', {
url: '/parent',
resolve: {
stateToGo: function(service) {
if (service.getItems().length > 0) {
return 'child1';
} else {
return 'child2';
}
}
},
onEnter: function(stateToGo, $state) {
$state.go(stateToGo);
}
})
.state('child1', {
templateUrl: 'child1.html',
resolve: {
service: function(service) {
return service;
}
},
controller: function($scope, service) {
console.log(service.getItems());
service.removeItem();
console.log(service.getItems());
}
}).state('child2', {
templateUrl: 'child2.html'
});
});
myapp.factory('service', [function() {
var items = [1, 2];
return {
getItems: function() {
return items;
},
removeItem: function() {
items.pop();
}
};
}]);

Related

Can I have a child state that is the index using ui-router?

My routes look like:
$stateProvider.state('repository', {
url: '/:host/:owner/:repository',
views: {
appView: {
templateUrl: '/templates/app/repository.html'
}
}
}).state('repository.analytics', {
views: {
repositoryView: {
templateUrl: '/templates/app/_repositoryAnalytics.html'
}
}
}).state('repository.commit', {
url: '/:host/:owner/:repository/commit/:commitHash',
views: {
repositoryView: {
templateUrl: '/templates/app/_repositoryCommit.html'
}
}
}).state('repository.file', {
url: '/file?path',
views: {
repositoryView: {
templateUrl: '/templates/app/_repositoryFile.html'
}
}
});
I want the base URL for all repository-like states, that's why I'm specifying the url there. As an example, if I didn't do it this way, I would have to specify everything as it's shown in the commit state. This is verbose and not something I want to do.
So is it possible to have a default child state for repository so that if someone is directed there, then that child view loads?
** UPDATE **
This seems to work just fine if I click through the app, but if I go to the /:host/:owner/:repository URL directly, the child view (analytics) never loads.
I don't know whether you can have a default child state, but you can set subview in that parent state. Like this:
$stateProvider.state('repository', {
url: '/:host/:owner/:repository',
views: {
appView: {
templateUrl: '/templates/app/repository.html'
},
'repositoryView#repository': { // it means the repositoryView of repository state.
templateUrl: '/templates/app/_repositoryAnalytics.html'
}
}
})
Then, when you open with repository state or URL, the analytics page will be loaded in repositoryView view of repo page.
[updated]
This format 'repositoryView#repository' means that, the view 'repositoryView' in the state 'repository'. Because you try to open the state 'repository', with a default sub-view. And the sub view 'repositoryView' is defined in 'repository.html'. If you didn't set the state scope, ui-router will think that the sub-view 'repositoryView' belongs to 'repository' 's parent view.
I don't know whether I explain it clearly, you can check the ui-router wiki
I created working plunker here. One way could be to use eventing to force go to child state, when parent is selected (resolved from url)
.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$on('$stateChangeStart', function(event, toState, toPrams) {
if (toState.name === "repository") {
event.preventDefault();
$state.go('repository.analytics', toPrams);
}
});
}
])
Check it here
Some other topics about redirections parent-child:
Angular UI-Router $urlRouterProvider .when not working when I click <a ui-sref="...">
Angular UI-Router $urlRouterProvider .when not working *anymore*

AngularJS - load data before loading any controller

I'm making a single page application (SPA). I made a controller called InitialControler to load the data from the server at this url (local.app/init).
I want this url to be opened before any other url. I'm using ui-router, I did a $state.go('init') in the .run() function but it still load the requested page before the 'init' page
First create state called app
$stateProvider.state('app', {
abstract: true,
templateUrl: "assets/partials/container.html",
controller: 'AppCtrl',
resolve: {
init: function(MyFactory) {
return MyFactory.resolver();
}
}
});
Now, any new state you create should be child state of app state. This is also good because it become sort of your root scope. And state will not process unless your factory resolves.
This is how you create your factory
app.factory('MyFactory', function($http){
var items = [];
return {
resolver: function(){
return $http.get('my/api').success(function(data){
items = data;
})
},
get() {
return items;
}
}
});
Now in any other state
$stateProvider.state('app.items', {
url: '/items',
templateUrl: "assets/partials/items.html",
controller: function($scope, MyFactory){
$scope.items = MyFactory.get();
}
});
More on sate resolve
https://github.com/angular-ui/ui-router/wiki#resolve
If you are using ui-router then you could resolve this using nested states. For example:
$stateProvider
.state("main", {
url: "/",
template: '<div ui-view></div>',
controller: 'InitController'
})
.state("main.landing", {
url: "landing",
templateUrl: "modules/home/views/landing.html",
controller: 'LandingPageController'
})
.state("main.profile", {
url: "profile",
templateUrl: "modules/home/views/profile.html",
controller: 'ProfileController'
});
In this example you have defined 3 routes: "/", "/landing", "/profile"
So, InitController (related to "/" route) gets called always, even if the user enters directly at /landing or /profile
Important: Don't forget to include <div ui-view></div> to enable the child states controller load on this section
One way to do is, in config declare only 'init' state. And in InitialController, after data is loaded(resolve function of service call), configure other states. But in this approach, whenever you refresh the page, the url will change to local.app.init.
To stay in that particular state even after reloading, the solution I found is to have a StartUp app in which I loaded the required data and after that I bootstraped the main app manually by angular.bootstrap.

Angular UI-router and using dynamic templates

I'm trying to load a template file using a rootscope value as for it's name.
I have a init controller which sets the $rootScope.template to "whatever.html", then I have my route like this:
$stateProvider.state('/', {
url: '/',
access: 'public',
views: {
page: {
controller: 'HomeCtrl',
templateProvider: function($templateFactory, $rootScope) {
return $templateFactory.fromUrl('/templates/' + $rootScope.template);
}
}
}
});
But this doesn't work. It actually freezes the whole chrome so that I have to kill the process in order to stop it... I've also tried this with templateUrl but with no results.
So how could I use my dynamic template file with UI-router?
Similiar to your other question (in order I found them): Angular and UI-Router, how to set a dynamic templateUrl, I also created a working plunker to show how to. How it would work?
So, if this would be state call:
#/parent/child/1
#/parent/child/2
And these would be states:
$stateProvider
.state('parent', {
url: '/parent',
//abstract: true,
templateUrl: 'views.parentview.html',
controller: function($scope) {},
});
$stateProvider
.state('parent.child', {
url: '/child/:someSwitch',
views: {
// see more below
Then we can use this templateProvider definiton:
templateProvider: function($http, $stateParams, GetName) {
// async service to get template name from DB
return GetName
.get($stateParams.someSwitch)
// now we have a name
.then(function(obj){
return $http
// let's ask for a template
.get(obj.templateName)
.then(function(tpl){
// haleluja... return template
return tpl.data;
});
})
},
What we can see is chaining of async results:
// first return of promise
return asyncstuff
.then(function(x){
// second return of a promise once done first
return asyncstuff
.then(function(y){
// again
return asyncstuff
.then(function(z){
return ... it
}
}
}
And that's what the magical templateProvider can do for us... wait until all promises are resolved and continue execution with known template name and even its content. Check the example here. More about template provider: Angular UI Router: decide child state template on the basis of parent resolved object

Controlling order of operations with services and controllers

I have two services - one to store user details and the other to make a call to retrieve those details:
userService stores user details to be used across the entire app (i.e. injected in controllers, services, etc.)
function userService($log) {
var id = '';
var username = '';
var isAuthenticated = false;
var service = {
id: id,
username: username,
isAuthenticated: isAuthenticated
};
return service;
}
authService is used (hopefully just once) to retrieve the user details from a Web API controller:
function authService($log, $http, userService) {
$log.info(serviceId + ': Inside authService method');
var service = {
getUserDetails: getUserDetails
};
return service;
function getUserDetails() {
$log.info(serviceId + ': Inside getUserDetails method');
return $http.get('api/authentication', { cache: true });
}
}
Initially, I had the call to the authService fire in a .run block like so:
.run(['$log', 'authService', 'userService', function ($log, authService, userService) {
authService.getUserDetails()
.then(querySucceeded);
function querySucceeded(result) {
userService.id = result.data.Id;
userService.username = result.data.username;
}
}]);
But the problem was that the getUserDetails-returned promise did not resolve until after I my controllers fired and, thus, too late for me. The user data was not ready.
I then looked at the resolve option in the $stateProvider (for UI-Router):
.state('dashboard', {
url: '/dashboard',
views: {
header: {
templateUrl: 'app/partials/dashboard/header.template.html',
controller: 'DashboardHeaderController',
controllerAs: 'dashboardHeaderVM',
resolve: {
user: function (authService) {
return authService.getUserDetails();
}
}
}
}
})
The assumption is that the view won't be rendered until the promise in the resolve section is, well, resolved. That seems to work fine.
Here's the (relevant part of the) controller where I use the returned user property:
function DashboardHeaderController($log, user) {
var vm = this;
// Bindable members
vm.firstName = user.data.firstName;
}
However, I have two routes (more to come) and a user can navigate to either one. Do I need to have a resolve property in each state section for the authService? I want to fire the call to authService.getUserDetails just once no matter which route is served and have it available after that for any route, controller, etc.
Is there a better (best practice) way to do this?
Not sure about better or best practice, but here is a plunker with my way.
The point is to move resolve into some parent root state. The one who is ancestor of all states in the application:
$stateProvider
.state('root', {
abstract : true,
// see controller def below
controller : 'RootCtrl',
// this is template, discussed below - very important
template: '<div ui-view></div>',
// resolve used only once, but for available for all child states
resolve: {
user: function (authService) {
return authService.getUserDetails();
}
}
})
This is a root state with resolve. The only state with resolve. Here is an example of its first child (any other would be defined similar way:
$stateProvider
.state('index', {
url: '/',
parent : 'root',
...
This approach will work out of the box. I just would like to mention that if the 'RootCtrl' is defined like this:
.controller('RootCtrl', function($scope,user){
$scope.user = user;
})
we should understand the UI-Router inheritance. See:
Scope Inheritance by View Hierarchy Only
small cite:
Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).
It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states...
More explanation could be found in this Q & A
So, what does it mean?
Our root view can pass the resolved stuff into child state only - if their views are nested.
For example, the $scope.user will be inherited in child states/views/$scopes only if they are nested like this
.state('index', {
url: '/',
parent : 'root',
views: {
'' : { // the root view and its scope is now the ancestor
// so $scope.user is available in every child view
templateUrl: 'layout.html',
controller: 'IndexCtrl'
},
'top#index' : { templateUrl: 'tpl.top.html',},
'left#index' : { templateUrl: 'tpl.left.html',},
'main#index' : { templateUrl: 'tpl.main.html',},
},
Check it here
If I correctly understand you want that on page load you would have user info before any controller or service request it.
I had similar task in my current project.
To solve the problem I manually requested current user info before app bootstapping & store it in localStorage.
Then after app bootstrapping all controllers/services have accesss to current user info.
TIP: to get user info before app bootstrap you can still use $http service by manually injecting it:
angular.injector(['ng']).get('$http');

AngularJS UI-Router scoping issues

I've got what I think is a scoping issue with angular ui-router, but I'm not quite sure.
angular.module('Meeting').controller('MeetingController', ['$scope', 'signalRService', '$stateParams', function ($scope, signalRService, $stateParams) {
$scope.setMeetings = function(meetings) {
$scope.meetings = meetings.map(function(meeting) {
return {
id: meeting.CategoryId,
name: meeting.MeetingName
};
});
$scope.$apply();
};
$scope.connectToSignalR = function () {
signalRService.connect();
signalRService.registerAddMeetingsClientMethod($scope.addMeetings);
};
$scope.requestMeetings = function() {
signalRService.requestMeetings($stateParams.departmentId);
};
$scope.connectToSignalR();
$scope.eventId = $stateParams.eventId;
}]);
Basically, my module is injected with a signalR service, and I register a callback on it to set meetings. I have a button on my view to tell the signalR service to fetch the meetings, which then calls the callback I just registered.
Now, all this works fine with ui-router, but only the first time the page is loaded. Here's my routing config:
angular.module('Meeting')
.config(
['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state("meeting",
{
url: "/meeting/:departmentId/",
templateUrl: '/home/meetingPage',
controller: "MeetingController"
})
.state("meeting.members",
{
url: "/members/",
templateUrl: "/home/memberspage",
controller: "MeetingMemberController"
})
.state("meeting.edit", {
url: "/meetingedit",
views: {
'meetingtime': {
templateUrl: '/home/timepage',
controller: 'MeetingTimeController'
},
'location': {
templateUrl: '/home/locationpage',
controller: 'MeetingLocationController'
}
}
});
}]);
When I load up a meeting state (i.e. mysite/meeting/3), all the signalR methods are called, the meeting model in the MeetingController is populated, and the data appears in the view.
When I navigate to another state (i.e. mysite/meeting/4), the signalR methods are still called, and the meeting model is populated, but then just disappears. If I manually refresh the page with F5, it starts to work again, but navigating to a different page stops everything working.
I'm thinking it's a scoping issue, because when I navigate to a different page, the meetings object is still populated from the previous page.
The way I was registering callbacks with a singleton signalR service was getting really cumbersome, and doesn't play well with ui-router, as I found out.
I switched to using promises, and everything works so much more elegantly. Basically, I have a method on my signalR hub that returns the object I want:
public List<Meeting> GetMeetingsForMember(int memberId)
{
return _meetingRepository.GetAllUpcomingMeetingsForMember(int memberId);
}
Then, in my controller, I create a promise, and pass it to my signalR service for resolution:
var deferred = $q.defer();
deferred.promise.then(
function (meetings) {
setMeetings(meetings);
}
);
signalRService.getMeetingsForMember(memberId, deferred);
The getMeetingsForMember method on my signalR service accepts the promise and resolves it:
getMeetingsForMember = function (memberId, deferred) {
deferred.resolve(signalRService.hub.server.getMeetingsForMember(memberId));
}

Resources