Manoj Shevate
Manoj Shevate

Reputation: 742

Persisting $scope while switching state using ui-router

I am creating AngularJS app for tutorials where I need to populate tutorial data from service and show it in three panels on UI. First panel contains list of Topics, 2nd - list of subtopics and 3rd one contains data.

initially when we haven't selected any topics, service should return subtopics of 1 topic and data of the 1st subtopic.

While you click on any other subtopic, then service should return the data for the give subtopic. But as soon as the state gets changed controller is getting re-instantiated and losing the data of topic/subtopic list which we initially shown on UI.

Please refer POC at http://embed.plnkr.co/v16rd5v1IjB14btfY7PQ/

possible solution - when we click on any of the subtopic, we should overpopulate tops/subtopics data somewhere from localstorage or sessionStorage and merge it with the service data which will have the desired output.

Is there any other way to implement 3 level dynamic navigation using Angular?

Upvotes: 4

Views: 77

Answers (2)

vorillaz
vorillaz

Reputation: 6266

As you perfectly mentioned localstorage is always a good to go method for data storage. I personally prefer using a $rootscope model to pass data around the states.

app.controller('topicController', ['$scope','TopicProvider','$rootScope',function($scope,TopicProvider,$rootScope){

  var t = TopicProvider.get(function(tp){
    $scope.t = tp.topics;
    $scope.st = tp.subtopics;
    $scope.d = tp.data;
  });
  //pass data between the states
  $rootScope.dummyModel = "test";
}]);



app.controller('anotherController', ['$scope','TopicProvider','$rootScope',function($scope,TopicProvider,$rootScope){
  //get that model
  alert($rootScope.dummyModel);
}]);

Upvotes: 3

Martin Schulz
Martin Schulz

Reputation: 592

You can store your data in service, it will not reset after state change.

Here is the similar question.

Upvotes: 3

Related Questions