Skip to content Skip to sidebar Skip to footer

How Can I Change Params In Url With Angularjs?

I want change the url in my angularjs app on the fly by tipping in a inputfield. e.g. I stay on: http://localhost/test/year/2012 I will change on the side via a input field the y

Solution 1:

$location.search will create an url like:

http://localhost/test/year/2012?year=2013

which is not what you want. You need to use $location.url():

functionOverviewCtrl($scope,$routeParams, $location) {
      $scope.yearIsChanged = function () {
        $location.url('/test/year/' + $scope.year);
    }   
}

Solution 2:

Actually if you'll use 'search' then $location service will change 'search' part of URL, see URL spec. So AngularJS will detect that routing would not be changed and has possibility not to reload controller (reloadOnSearch:false).

But using .url or .path methods can change whole URLs, but AngularJS router can't detect can it re-use controller or not. So the only option is apply routing table to new url and re-initialize routes.

To achieve your goal (specific urls like /year/2012) without re-loading controller, you can:

  1. rewrite ngView directive (and possible some changes to default routing in AngularJS) and try to re-use scopes. This sounds like quite havy change.

  2. Don't use default AngularJS routing and implement desired behaviour by yourself.

Here is sample Plunker that illustrates second option (press small blue button in preview pane to see how URL changes, and also check that prev/next browser's buttons do not reload page/controller).

Solution 3:

You should notice that in your route :

"when (' / test / year / : year ' "

the BOLD word , is a routeParam and is not search fileds.

So if you want to change your route , you should use this :

functionOverviewCtrl($scope,$routeParams, $location) {
      $scope.yearIsChanged = function () {
       $location.path('/test/year/'+$scope.year)
     // .path() will set(or get) your routeParams // .search() will set(or get) your seach fields like your error
     }   
   }

Post a Comment for "How Can I Change Params In Url With Angularjs?"