Change route route without reloading controller and template in angularjs route
Hi all angularjs devs, I followed the ng doc ( link ). I have searched many times but I have not found any solution this will help me correctly. I need to change the route without reloading the controller and template. I wrote a route that looks like this: -
$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' });
Also, first I go to page1, then page2, and then through page3, after that I now want to go to page1 without reloading or calling the page1Ctrl and page1 template. Example: Suppose when I was page1 I was working on that I selected the ng-grid entry which was paging size 3 and I entered some fields. After that I will go to page 3, then go to page 1 again. Now this time I want to see page1 that I selected the ng grid entry and what I entered. How can I solve this? Thank.
source to share
To preserve data when it is removed from the controller and then back again, it is recommended to use the Angular approach to using services. See this NG-Conf talk: https://www.youtube.com/watch?v=62RvRQuMVyg .
To keep the input fields and paging index when exiting page1Ctrl, then for example, you can create a pagingModelService.
function PagingModelService($rootScope)
{
var pagingModelService = {};
////////////////////
// persisted data //
////////////////////
pagingModelService.pagingIndex;
pagingModelService.field1;
pagingModelService.field2;
////////
//Init//
////////
return(pagingModelService);
}
Then inject the service into 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;
}
Alternatively, you can have a look at angular-local-storage for persisting data: https://github.com/grevory/angular-local-storage
source to share