Angularjs: use config only for one controller

183 Views Asked by At

On one page I load content via ajax according to user picks (filters), to ensure that loaded content stays in place if user reloads or lands on the page, I put the picked filters into the url query string. Since I load the content via ajax on this particular page I don't need to reload the entire page every time a new filter is picked by the user, so I prevent browser to react on url change with the following config:

app.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

However this affects the entire app and prevents all other pages from reloading on url change, the behavior I don't want. How can I make this configuration to affect only one particular controller within my app?

3

There are 3 best solutions below

1
On

If your goal is to prevent reloading the page when the query string changes, html5Mode is entirely the wrong tool for the job. You want reloadOnSearch: false which can be applied globally or to individual routes:

$routeProvider
  .when('/foo', {
    controller: 'fooCtrl',
    templateUrl: 'foo.html',
    reloadOnSearch: false
  },
  ...
);

https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

0
On

From Angular's documentation on $locationProvider, maybe the cause of that behavior is by design:

  • rewriteLinks - {boolean} - (default: true) When html5Mode is enabled, enables/disables url rewriting for relative links.

If your app is reacting to the url to make a change as a sort of RESTful api I would recommend using ngRoute or even better uiRouter.

Hope that helps.

0
On

This is a tricky situation, and you might not like my suggestion; heck I don't even like this suggestion because it breaks the whole awesomeness of a single page application.

But what you could do, is to create a separate html file (lets call it pick-filters.html). On that new html file, have a new ng-app and therefore a separate app.js file for this particular page. In this new app.js file (lets call it pick-filters-app.js), you can use the app.config snippet that you have shown here. This should fix your problem of all pages not reloading because only pick-filters.html is referencing pick-filters-app.js which has this config snippet.