Disable URL change with UI-Router in Angular? - angularjs

Is it possible to configure ui-router in an Angular 1.5 application to completely ignore the address bar?
Desired behaviour is something like this:
Navigating between states via UI does not change the URL
Changing the URL does not cause navigation between states, only UI or programmatic actions do (clicking the buttons, etc.)
Hitting F5 restarts the application from "default" controller
Original URL (especially query parameters) must still be accessible
UPDATE: I am creating an application with a very specific use case, not a website. Ordinary web browsing practices do not apply here. Please accept the requirements as they are, even if it may seem to contradict common sense.

Agreed that the stated approach is not good if we consider classic web app.
I tried to create a sample application with your requirement in mind.
Here is how my router configuration(router.config.js) file looks like in my fruits app:
.state('start', {
url: '/',
templateUrl: '../app/start/start.html',
controller: 'startCtrl as vm',
})
.state('fruits', {
templateUrl: '../app/fruits/fruitshtml',
controller: 'fruitsCtrl as vm',
})
.state('fruits.details', {
params: {
fruitId: undefined
},
templateUrl: '../app/fruits/fruitdetails.html',
controller: 'fruitDetailsCtrl as vm'
})
Explanation of States:
start:
url / is entry point of my application. If url is /, start state will be loaded.
fruits:
This state shows list of fruits in my app. Note that there is no url defined for this state. So, if we go to this state, url won't change (State will change, but url won't).
fruits.details:
This state should show detail of a fruit with id fruitId. Notice we have passed fruitId in params. params is used to pass parameters without using the url! So, passing of parameters is sorted. I can write ui-sref="fruit.details({ fruitId: my-fruit-id })" to navigate to fruit.details state and show details of my fruit with fruitId my-fruit-id.
As you might have already got it, the main idea is to use states as means of navigation.
Does my app pass your points?
Navigating between states via UI does not change the URL
Changing the URL does not cause navigation between states, only UI or programmatic actions do (clicking the buttons, etc.)
Hitting F5 restarts the application from "default" controller
Original URL (especially query parameters) must still be accessible
->
pass: as we haven't defined url for states
pass: changing url will change to state to start. The app will not take user to any different state, but it does changes state to start or we could say our default state.
pass: refresh will take you to start state
pass: if you write start in your url, you app will got start state.
Possible work around for the 2nd point, which is not passed completely: We can write code to check the url (in startCtrl controller) passed. If url contains extra things appended to /start, go to previous state. If url is 'start' continue loading start page.
Update:
As pointed by OP #Impworks, solution for 2nd point is also passed if we set url of our start state to /. This way, if we append any string to url, the state won't change.

Related

angularjs ui-router: redirect vs multiple url for same state

When I navigate first to my index page where the url is '/', I want to display the content of the state '/matches'. What you think is better?
I can use
$urlRouterProvider.otherwise('/matches');
that works, but I know it's not a good solution.
So I have to choose between
1- redirecting / to /matches and I tried
$urlRouterProvider.when('/','/matches');
but it didn't work.
2- specify multiple paths / and /matches to the same state matches which I don't know how to do.
In ng-route I used to do it like this:
.when('/', {
redirectTo : '/matches'
})
but I don't think it's good to combine ng-route with ui-router.
I found a perfect solution
app.run(function($state){
$state.go('/matches');
});
Once the app runs, I call the state that I want to load using $state.go and I also kept the
$urlRouterProvider.otherwise('/matches');
in case the user tries to enter an invalid url (state), he will be redirected to the initial state.

How to update only browser url, not the state in AngularJs

Lets say, there is application, that can be run for different units, with different names. Before, when user select another unit, we just reinstating controller, and load new data for new unit, this changes was not reflected on url. But, now we need to add unit name to the url.
For example we have following state:
$stateProvider.state('management', {
url: '/management',
templateUrl: 'features/management/templates/management.html'
});
And in browser we can see:
http://localhost:84/#/management
Now, when we go to that state, I need browser to show something like this:
http://localhost:84/#/unitName/management
For example we have unit1, unit2, unit3, and when user switch between them, url will be changed to
http://localhost:84/#/unit1/management,
http://localhost:84/#/unit2/management,
http://localhost:84/#/unit3/management
and so on.
I can get unitName from service, for example unitService.js that will return me a unit name as a string. But I have no idea how to add this string to url in browser. This unit name should be added to all routes, but without changing them.
Can I make first function, that will add unit name to browser url after all data was loaded, and second function, that will remove that string when angular starts to searching for state by url, so instead of unit1/management it will look for /management state?
Is it possible? Thank you in advance.
You can use notify: false.
Route declaration
$stateProvider.state('management', {
url: '/:unit/management',
templateUrl: 'features/management/templates/management.html'
});
State go example
$state.go('management', {unit: 'unit1'}, {notify: false})

Angular UI Router with multiple optional parameters

I have a state route as follows :
.state("hospitals",
{
url: "/hospitals/:categoryName/:providerName",
templateUrl: "app/components/hospital/views/hospitals.html"
})
In general,hospitals pages have all the hospitals with all categories and all provider(hospital) group. In addition, from home page we can navigate to the hospitals page using the category or provider which will show hospitals based on category and provider group respectively. For these, I navigate using the following directives inside anchor tag.
ui-sref="hospitals({categoryName: category.KeyName})"
ui-sref="hospitals({providerName: provider.KeyName})"
So, this introduces a dirty slash when navigating with providerName.
hospitals//somehopitalNme
It is fine with category.
coupons/heart/
Once inside the hospitals page, I can search using category or providerName and get the list of hospitals. I was thinking of modifying the url in these searches(using ui-sref for the same page) since it makes sense to show the url matching to the search. I land in a trouble here. The search is a common search and can match either providerName or category or even a text as well. In this case, how can I navigate or how to use s-ref. I am fine with not using ui-sref and just going to the api or getting the data and updating the results which is easily achievable. However, I prefer the change of url since it shows what we are looking for.
So, now I understand that the state route which I provided is not suitable.
Please provide me an approach as to how to do it.
I was thinking of adding another state called "search" for this, which makes sense. But the templateUrl for this will be the same. Please suggest if I am in right direction or not.
Check this for detailed explanation and working example
Angular UI-Router more Optional Parameters in one State
we can use so called squash setting of the params : {} object:
.state("hospitals",
{
url: "/hospitals/:categoryName/:providerName",
templateUrl: "app/components/hospital/views/hospitals.html",
params: {
providerName: { squash: true },
categoryName: { squash: true },
},
})
Also check these:
Angular js - route-ui add default parmeter
Option url path UI-Router

Angurlarjs: How to represent state in URL and get state back from URL?

I'm working on a search app using AngularJs 1.0.8.
In order to allow bookmarking and sharing links I want to represent the current state of the search in the browser's location bar.
A URL might look like this
http://example.com/#!/search?s="Some query term"&page=2
So the app has to do two things:
update the URL when someone searches
Restore the state when another opens the same URL
What I currently do (maybe this is the wrong approach) is:
Configuring routeProvider to prevent the browsers from reloading on search param changes
...
$routeProvider.when('/search', {
templateUrl: 'app/search/view/List.html',
controller: 'listCtrl',
reloadOnSearch: false
});
...
Getting search results and setting location when someone presses the search button (searchArray holds the search parameters)
...
$location.search(searchArray);
...
Updating the search results accordingly.
...
$scope.search_results=data;
...
In order to restore the state I'm watching $location.search()
...
$scope.$watch(function () { return $location.search() }, function (newVal) {/* evaluate params and fire query */ });
...
My problem is, that location always changes twice. I've managed to overcome this issue by maintaining dirty flag.
As I think this maintaining state in URL is a popular scenario, I think there must be a better approach with Angular.
Could anyone guide me in to the right direction?

Updating URL in Angular JS without re-rendering view

I'm building a dashboard system in AngularJS and I'm running into an issue with setting the url via $location.path
In our dashboard, we have a bunch of widgets. Each shows a larger maximized view when you click on it. We are trying to setup deep linking to allow users to link to a dashboard with a widget maximized.
Currently, we have 2 routes that look like /dashboard/:dashboardId and /dashboard/:dashboardId/:maximizedWidgetId
When a user maximizes a widget, we update the url using $location.path, but this is causing the view to re-render. Since we have all of the data, we don't want to reload the whole view, we just want to update the URL. Is there a way to set the url without causing the view to re-render?
HTML5Mode is set to true.
In fact, a view will be rendered everytime you change a url. Thats how $routeProvider works in Angular but you can pass maximizeWidgetId as a querystring which does not re-render a view.
App.config(function($routeProvider) {
$routeProvider.when('/dashboard/:dashboardId', {reloadOnSearch: false});
});
When you click a widget to maximize:
Maximum This Widget
or
$location.search('maximizeWidgetId', 1);
The URL in addressbar would change to http://app.com/dashboard/1?maximizeWidgetId=1
You can even watch when search changes in the URL (from one widget to another)
$scope.$on('$routeUpdate', function(scope, next, current) {
// Minimize the current widget and maximize the new one
});
You can set the reloadOnSearch property of $routeProvider to false.
Possible duplicate question : Can you change a path without reloading the controller in AngularJS?
Regards
For those who need change full path() without controllers reload
Here is plugin: https://github.com/anglibs/angular-location-update
Usage:
$location.update_path('/notes/1');
I realize this is an old question, but since it took me a good day and a half to find the answer, so here goes.
You do not need to convert your path into query strings if you use angular-ui-router.
Currently, due to what may be considered as a bug, setting reloadOnSearch: false on a state will result in being able to change the route without reloading the view. The GitHub user lmessinger was even kind enough to provide a demo of it. You can find the link from his comment linked above.
Basically all you need to do is:
Use ui-router instead of ngRoute
In your states, declare the ones you wish with reloadOnSearch: false
In my app, I have an category listing view, from which you can get to another category using a state like this:
$stateProvider.state('articles.list', {
url: '{categorySlug}',
templateUrl: 'partials/article-list.html',
controller: 'ArticleListCtrl',
reloadOnSearch: false
});
That's it. Hope this helps!
We're using Angular UI Router instead of built-in routes for a similar scenario. It doesn't seem to re-instantiate the controller and re-render the entire view.
How I've implemented it:
(my solution mostly for cases when you need to change whole route, not sub-parts)
I have page with menu (menuPage) and data should not be cleaned on navigation (there is a lot of inputs on each page and user will be very very unhappy if data will disappear accidentally).
turn off $routeProvider
in mainPage controller add two divs with custom directive attribute - each directive contains only 'templateUrl' and 'scope: true'
<div ng-show="tab=='tab_name'" data-tab_name-page></div>
mainPage controller contains lines to simulate routing:
if (!$scope.tab && $location.path()) {
$scope.tab = $location.path().substr(1);
}
$scope.setTab = function(tab) {
$scope.tab = tab;
$location.path('/'+tab);
};
That's all. Little bit ugly to have separate directive for each page, but usage of dynamic templateUrl (as function) in directive provokes re-rendering of page (and loosing data of inputs).
If I understood your question right, you want to,
Maximize the widget when the user is on /dashboard/:dashboardId and he maximizes the widget.
You want the user to have the ability to come back to /dashboard/:dashboardId/:maximizedWidgetId and still see the widget maximized.
You can configure only the first route in the routerConfig and use RouteParams to identify if the maximized widget is passed in the params in the controller of this configured route and maximize the one passed as the param. If the user is maximizing it the first time, share the url to this maximized view with the maximizedWidgetId on the UI.
As long as you use $location(which is just a wrapper over native location object) to update the path it will refresh the view.
I have an idea to use
window.history.replaceState('Object', 'Title', '/new-url');
If you do this and a digest cycle happens it will completely mangle things up. However if you set it back to the correct url that angular expects it's ok. So in theory you could store the correct url that angular expects and reset it just before you know a digest fires.
I've not tested this though.
Below code will let you change url without redirection such as: http://localhost/#/691?foo?bar?blabla
for(var i=0;i<=1000;i++) $routeProvider.when('/'+i, {templateUrl: "tabPages/"+i+".html",reloadOnSearch: false});
But when you change to http://localhost/#/692, you will be redirected.

Resources