Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access route parameters outside the view

Tags:

angularjs

I'm writing a very simple Angular app for showing information about football tournaments. For each tournament in the database I want to show a view of either the matches or the statistics, so I'm implementing this simple URL scheme:

  • foo/matches: matches of tournament Foo,
  • foo/stats: statistics for tournament Foo.

The index.html file is structured like this:

<nav ng-controller="NavController">
  <ul>
    <li> <a href="#/{{ t }}/matches"> Matches </a> 
    <li> <a href="#/{{ t }}/status">  Stats </a>
  </ul>
</nav>

<div ng-view></div>

and the routes are configured like this:

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when('/:t/matches', {templateUrl: 'partials/matches.html', controller: 'MatchesController'})
    .when('/:t/stats',   {templateUrl: 'partials/stats.html',   controller: 'StatsController'  })
}]);

My problem are those {{ t }} links in the HTML. I want the links to change the view to the stats or the match list for the current tournament. But since the links are outside the view, so they don't have access to the route parameters (I tried injecting $routeParams and all I get is an empty object).

In summary, I haven't been able to create links for changing the view outside of it. The nav bar doesn't know what is the current tournament.

How can I (and what is the best way to) access the current state of the view (in this case, the current tournament) outside of it?

like image 227
Roberto Bonvallet Avatar asked Sep 10 '13 00:09

Roberto Bonvallet


2 Answers

After reading a bit about scopes I learned how they nest. I solved my problem simply by wrapping both the view and the navigation bar with a new controller:

<div ng-controller="NavController">

  <nav>
    <ul>
      <li> <a href="#/{{ t }}/matches"> Matches </a> 
      <li> <a href="#/{{ t }}/status">  Stats </a>
    </ul>
  </nav>

  <div ng-view></div>

</div>

The view will inherit NavController's scope prototypically. I initialized an object in the outer scope, and assigned the desired value to one of its properties in the inner controllers:

 app.controller('NavController', function ($scope) {
     $scope.currentTournament = {};
 });

 app.controller('MatchesController', function ($scope, $routeParams) {
     // ...
     $scope.currentTournament.id = $routeParams.t;
 });

 app.controller('StatsController', function ($scope, $routeParams) {
     // ...
     $scope.currentTournament.id = $routeParams.t;
 });
like image 152
Roberto Bonvallet Avatar answered Nov 09 '22 14:11

Roberto Bonvallet


If you are using ui-router, you could use the $stateParams service to access state and state variables from anywhere in your app.

like image 41
Jeremy Smith Avatar answered Nov 09 '22 12:11

Jeremy Smith