AngularJS ui-router state doesn't refresh on back - angularjs

I have an app setup with 2 states, A and A.B done this way:
$stateProvider.state('A', {
url: "/A/{aId}",
controller: 'AController',
templateUrl: function($stateParams) {
return "/A/" + $stateParams.aId + "/layout";
}
}).state('A.B', {
url: "/B/{bId}",
controller: 'BController',
templateUrl: function($stateParams) {
return "/A/" + $stateParams.aId + "/B/" + $stateParams.bId+ "/layout";
}
});
When I'm in state A.B ( the url would be somthing like #/A/12/B/123 ) and go back using the back button of the browser or transitionTo the url changes, state A.B is cleared but state A doesn't render back. As far as I can tell the controller isn't triggered.
So if I'm in A/12/B/123 and go back to A/12 nothing happens, but if I go back to A/13 ( using transitionTo ) it renders.
On the sample app from angular-ui-router project this scenario works fine, so I think there might be something wrong in my setup. I think it's worth mentioning that on index.html I have a ui-view which loades state A and the template for state A has another ui-view that loads state A.B
If anyone could help, I would really appreciate it

Have you tried using this:
$state.reload()
Its a method that force reloads the current state. All resolves are re-resolved, events are not re-fired, and controllers reinstantiated
This is just an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: false
});

Related

Navigate back to state without reloading template

I have done some research but couldn't find a definitive answer. I have main application area where I load different screens. From one screen I want to open a page that would cover the whole screen. So, navigating to 'viewreport' does exactly that. And when I click on Browser's Back button or have my own Back button on the whole screen page I want to get back to the previous state without reloading its template and controller. Another words, I want to see all selections I have done prior opening the whole screen page. Here is my state configuration:
$stateProvider
.state('body', {
url: '/',
abstract: true,
template: '<div ui-view />'
})
.state('viewreport', {
url: 'viewreport',
templateUrl: 'wholescreen.html',
controller: 'wholescreenController'
});
I am loading different modules into the main 'body' state which might look like this:
function ($stateProvider) {
$stateProvider.state('body.htmlreports', {
templateUrl: function ($stateParams) {
return 'htmlReports.html';
},
controller: 'htmlReportsController',
url: 'htmlreports',
}).state('body.htmlreports.reportarea', {
templateUrl: 'htmlReportParams.html',
controller: 'htmlReportParamsController',
});
I am navigating to viewreport state from htmlReportParamsController controler. The new page then opens into the whole screen. That part works fine. But navigating back to htmlreports when clicking on the Browser's Back button will reload 'body.htmlreports' state. Is there a way of getting back to it without reloading its template?
Update. Why I think it's not a duplicate.
I tried what's suggested in it before posting. This: $state.transitionTo('yourState', params, {notify: false});
still reloads 'yourState'. Also the use case in the provided link is not exactly as mine. Because the OP uses edit mode for already loaded view while I am loading a new view over the the whole screen.
Thanks
Use
$window.history.back();
Add $window in dependency injections of your controller. This will refresh your page and wont reload data we selected.
Please maintain states like this
function ($stateProvider) {
$stateProvider.state('body.htmlreports', {
templateUrl: function ($stateParams) {
return 'htmlReports.html';
},
controller: 'htmlReportsController',
url: 'htmlreports',
}).state('body.htmlreports.reportarea', {
templateUrl: 'htmlReportParams.html',
controller: 'htmlReportParamsController',
}).state('body.htmlreports.reportarea.viewreport', {
url: 'viewreport'
});

Angular ui-router bound state to URL

I'm struggling with this counfiguration of $stateProvider and $urlRouterProvider for days now.
My problem is, in fact, that after I use $state.go(), state changes normally, but url in browser stays the same (#/).
Additionaly, when I set the $urlRouterProvider.otherwise('home'); option, after every $state.go() router redirects to /home, no matter what state was picked.
My configuration:
StateConfiguration.$inject = ['$stateProvider', '$urlRouterProvider'];
function StateConfiguration($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('home');
addState("state1", "/state1", "<example-page></example-page>");
addState("state2", "/state2", "<example-page2></example-page2>");
addState("register", "/register", "<register-page></register-page>");
addState("error", "/error", "<error-page></error-page>", {
error: null
});
addState("myLibrary", "/my-library/{groupId}{groupName}", "<my-library></my-library>", {
groupId: null,
groupName: null
});
addState("home", "/home", "<main-page></main-page>");
///////////////////////////
function addState(stateName, url, template, params){
$stateProvider.state(
stateName,
{
url: url,
template: template,
params: params || {}
}
);
}
}
Can somebody point me, where I have error? Every state just uses another directive.
My goal is that when application changes state, the url in browser changes as well. Additionally, when user enter url like app.com/state-url, application redirects to state with url state-url. How should I do it?
UPDATE
As requested, I'm adding $state.go() calls, but they're not very "big".
service.home = function(params){
$state.go("home", params);
};
service.register = function(params){
$state.go("register", params);
};
Also, after looking closer, after going to register state, url changes for 0.5 s to register and then, goes back to home.
Your use of this is wrong:
$urlRouterProvider.otherwise('home');
The clue is in the name (urlRouterProvider) - it deals with url, not state, so you should do it like this:
$urlRouterProvider.otherwise('/home');
I can't comment on your $state.go calls, because you haven't provided examples of those.

AngularJS. Retain state after page reload

I am using UI Router with html5Mode enabled, states are loaded from JSON.
Expected behavior after F5 or when pasting URL is, respectively, having current state reloaded or navigating to the said state, instead the initial application state is loaded.
For e.g. root/parent/child gets redirected to root/.
By the way, navigating with ui-sref works fine.
So, how can the state be retained after page reload?
In order to retain the state of page after reload app, a url represent the state should be gave. when you include ui-route module, url will be parsed and sent to corresponding state. You don't need to parse the url handly in most cases, ui-route born to do this.
Please can you post your code here? Specifically the $stateProvider.
This is an example of a correct $stateProvider and it works fine:
$stateProvider.state('main.admin', {
url: '/admin',
resolve: {},
views: {
'main-content#main': {
controller: 'AdminController as admin',
templateUrl: 'main/admin/admin.tpl.html'
}
}
});
Seems a bit hacky, but works for now.
app.run(['$location', '$state', function ($location, $state) {
function stateFromUrl () {
var path = $location.path(),
hash = $location.hash();
// do JSON states map parsing and find a corresponding to the URL state
return state;
}
if (stateFromUrl) {
$state.go(stateFromUrl);
} else {
$state.go('home'); // initial state
}
}]);

Change route path without reloading controller and template in angularjs route

Hi all angularjs developer, I have followed the ng document (link) .I have searched since many times but i did not find any solution that will help me properly. I need to change route without reloading the controller and template. I have written a route that look like this below:-
$routeProvider
.when('/page1', {
templateUrl: 'page1',
controller: 'page1Ctrl',
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.when('/page2', {
templateUrl: 'page2',
controller: 'page2Ctrl',
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.when('/page3', {
templateUrl: 'page3',
controller: 'page3Ctrl',
caseInsensitiveMatch: true,
reloadOnSearch: false
}).otherwise({ redirectTo: '/index' });
Moreover, at first I go to the page1 then page2 then page3 after that now i want to go to the page1 without reloading or calling page1Ctrl and page1 template. Example: suppose when i was page1 that time i have worked something like i have selected an ng-grid record which was paging size 3 and i have inputted some fields. After that i go the page3 then i go to the page1 again. Now this time i want to see the page1 what i selected ng grid record and what i inputted. How can i solve this? Thanks.
I want to suggest to use Angular Ui.router
you will have the ability to change the state of routes , for more check the documentation
To persist data when moving away from a controller and then back again, the recommended Angular approach is to use services. See this NG-Conf talk: https://www.youtube.com/watch?v=62RvRQuMVyg.
To persist input fields and paging index when leaving page1Ctrl and then returning, for example, you could create a pagingModelService.
function PagingModelService($rootScope)
{
var pagingModelService = {};
////////////////////
// persisted data //
////////////////////
pagingModelService.pagingIndex;
pagingModelService.field1;
pagingModelService.field2;
////////
//Init//
////////
return(pagingModelService);
}
Then inject the service in the controller, and set the $scope values to the service:
function Page1Ctrl($scope, pagingModelServiceModel)
{
///////////////////////////////////////////////////
//set local $scope variables to persisted service//
///////////////////////////////////////////////////
$scope.pageIndex = pagingModelService.pagingIndex;
$scope.field1 = pagingModelService.field1;
$scope.field2 = pagingModelService.field2;
}
Also, you can look into angular-local-storage for persisting data: https://github.com/grevory/angular-local-storage

How to reload the current state?

I'm using Angular UI Router and would like to reload the current state and refresh all data / re-run the controllers for the current state and it's parent.
I have 3 state levels: directory.organisations.details
directory.organisations contains a table with a list of organisations. Clicking on an item in the table loads directory.organisations.details with $StateParams passing the ID of the item. So in the details state I load the details for this item, edit them and then save data. All fine so far.
Now I need to reload this state and refresh all the data.
I have tried:
$state.transitionTo('directory.organisations');
Which goes to the parent state but doesn't reload the controller, I guess because the path hasn't changed. Ideally I just want to stay in the directory.organisations.details state and refresh all data in the parent too.
I have also tried:
$state.reload()
I have seen this on the API WIKI for $state.reload "(bug with controllers reinstantiating right now, fixing soon)."
Any help would be appreciated?
I found this to be the shortest working way to refresh with ui-router:
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams
Update for newer versions:
$state.reload();
Which is an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
Documentation: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_reload
This solution works in AngularJS V.1.2.2:
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
That would be the final solution. (inspired by #Hollan_Risley's post)
'use strict';
angular.module('app')
.config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});
Now, whenever you need to reload, simply call:
$state.forceReload();
for ionic framework
$state.transitionTo($state.current, $state.$current.params, { reload: true, inherit: true, notify: true });//reload
$stateProvider.
state('home', {
url: '/',
cache: false, //required
https://github.com/angular-ui/ui-router/issues/582
Probably the cleaner approach would be the following :
<a data-ui-sref="directory.organisations.details" data-ui-sref-opts="{reload: true}">Details State</a>
We can reload the state from the HTML only.
#Holland Risley 's answer is now available as an api in latest ui-router.
$state.reload();
A method that force reloads the current state. All resolves are
re-resolved, controllers reinstantiated, and events re-fired.
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state
$state.go($state.current, $stateParams, {reload: true, inherit: false});
$scope.reloadstat = function () { $state.go($state.current, {}, {reload: true}); };
if you want to reload your entire page, like it seems, just inject $window into your controller and then call
$window.location.href = '/';
but if you only want to reload your current view, inject $scope, $state and $stateParams (the latter just in case you need to have some parameters change in this upcoming reload, something like your page number), then call this within any controller method:
$stateParams.page = 1;
$state.reload();
AngularJS v1.3.15
angular-ui-router v0.2.15
Silly workaround that always works.
$state.go("otherState").then(function(){
$state.go("wantedState")
});
For angular v1.2.26, none of the above works. An ng-click that calls the above methods will have to be clicked twice in order to make the state reload.
So I ended up emulating 2 clicks using $timeout.
$provide.decorator('$state',
["$delegate", "$stateParams", '$timeout', function ($delegate, $stateParams, $timeout) {
$delegate.forceReload = function () {
var reload = function () {
$delegate.transitionTo($delegate.current, angular.copy($stateParams), {
reload: true,
inherit: true,
notify: true
})
};
reload();
$timeout(reload, 100);
};
return $delegate;
}]);
Everything failed for me. Only thing that worked...is adding cache-view="false" into the view which I want to reload when going to it.
from this issue https://github.com/angular-ui/ui-router/issues/582
Not sure why none of these seemed to work for me; the one that finally did it was:
$state.reload($state.current.name);
This was with Angular 1.4.0
I had multiple nested views and the goal was to reload only one with content.
I tried different approaches but the only thing that worked for me is:
//to reload
$stateParams.reload = !$stateParams.reload; //flip value of reload param
$state.go($state.current, $stateParams);
//state config
$stateProvider
.state('app.dashboard', {
url: '/',
templateUrl: 'app/components/dashboard/dashboard.tmpl.html',
controller: 'DashboardController',
controllerAs: 'vm',
params: {reload: false} //add reload param to a view you want to reload
});
In this case only needed view would be reloaded and caching would still work.
I know there have been a bunch of answers but the best way I have found to do this without causing a full page refresh is to create a dummy parameter on the route that I want to refresh and then when I call the route I pass in a random number to the dummy paramter.
.state("coverage.check.response", {
params: { coverageResponse: null, coverageResponseId: 0, updater: 1 },
views: {
"coverageResponse": {
templateUrl: "/Scripts/app/coverage/templates/coverageResponse.html",
controller: "coverageResponseController",
controllerAs: "vm"
}
}
})
and then the call to that route
$state.go("coverage.check.response", { coverageResponse: coverage, updater: Math.floor(Math.random() * 100000) + 1 });
Works like a charm and handles the resolves.
You can use #Rohan answer https://stackoverflow.com/a/23609343/3297761
But if you want to make each controller reaload after a view change you can use
myApp.config(function($ionicConfigProvider) { $ionicConfigProvider.views.maxCache(0); ... }
If you are using ionic v1, the above solution won't work since ionic has enabled template caching as part of $ionicConfigProvider.
Work around for that is a bit hacky - you have to set cache to 0 in ionic.angular.js file:
$ionicConfigProvider.views.maxCache(0);
I had this problem it was wrecking my head, my routing is read from a JSON file and then fed into a directive. I could click on a ui-state but I couldn't reload the page. So a collegue of mine showed me a nice little trick for it.
Get your Data
In your apps config create a loading state
Save the state you want to go to in the rootscope.
Set your location to "/loading" in your app.run
In the loading controller resolve the routing promise and then set the location to your intended target.
This worked for me.
Hope it helps

Resources