John
John

Reputation: 3946

How to have AngularJS router update a controller value upon navigation, rather than reloading the entire controller?

I have a large and complex view that is served on a route like /dailyReport/:dayId

When a user is navigating between different daily reports, I'd like to just update the DailyReportController with the new dayId rather than reloading the whole controller.

How can I do that?

Upvotes: 1

Views: 28

Answers (2)

Phil Degenhardt
Phil Degenhardt

Reputation: 7264

Wayne's answer is probably the simplest but it has the disadvantage of making your routes a little obscure.

Another approach would be to move the state, on which your view depends, from your controller/scope (instantiated for each navigation) to a service (singleton) that exposes a setDay() method. The controller would then take a dependency on the service, and simply call setDay() on each activation.

Upvotes: 0

Wayne Ellery
Wayne Ellery

Reputation: 7958

You could use $location.search() and reloadOnSearch: false and then pass the dayId in the query string:

.when('/dailyReport', {
    templateUrl: 'view.html',
    controller: 'MainCtrl',
    reloadOnSearch: false
})

To get notified on dayId change:

$scope.$on('$routeUpdate', function(){
  console.log($location.search().dayId);
});

Then to link to a new day:

<a href="#/dailyReport?dayId=2">Change day to 2</a>

Plunkr

Upvotes: 1

Related Questions