2

Here's something simple and I think there must be a better way: I often need to navigate to a new view, and at the same time I want to provide some context information to the scope that will be created. I can't figure out how to do both simply -- change the url (resulting in my view/controller being instantiated) and pass some variables I want instantiated in the controller's scope -- for instance, so they can be rendered in the view template

So instead I am doing:

$rootScope.myVar = 'blah';
$location.path = '/newView' ;

and newView.html accesses {{myVar}}

I know this is wrong, what is the simplest solution to avoid using $rootScope like a global dumping ground?

Tom
  • 7,640
  • 1
  • 23
  • 47
  • 1
    you should probably start with using a routing provider, either ui-router or the $routeProvider from angular, instead of using `$location.path` – Claies May 08 '15 at 20:21
  • 1
    You can either pass the state in a query parameter or store it in a service. Note: if you are not storing the state in the url then it will be lost when the page refreshes – rob May 08 '15 at 20:22
  • I'm actually including ui-router in my project, how would it be done using that? – Dave Horton May 08 '15 at 20:23
  • @rob - creating a service seems a bit heavyweight for this, using a query param would be ok, I guess, although I would prefer the variables not to be exposed in the url – Dave Horton May 08 '15 at 20:24
  • 1
    using ui-router, you can define your variables as parameters on the controller for the new page, or even use a `resolve` block to wait for variables to be looked up before loading. https://github.com/angular-ui/ui-router/wiki#resolve – Claies May 08 '15 at 20:36
  • Possible duplicate of [Is CacheFactory in angularjs a singleton?](https://stackoverflow.com/questions/15583403/is-cachefactory-in-angularjs-a-singleton) – Paul Sweatte Jul 10 '17 at 19:18

0 Answers0