AngularJS: Change hash and route without completely reloading controller

前端 未结 10 1226
鱼传尺愫
鱼传尺愫 2020-12-07 19:29

I have a controller, with a route like this:

#/articles/1234

I want to change the route without completely reloading the controller, so I can keep the positi

10条回答
  •  伪装坚强ぢ
    2020-12-07 20:13

    Brief Answer:

    You can use the $location.search() method as you mentioned. You should listen to the "$routeUpdate" event on scope instead of other route events. $route API.

    Explanation:

    1. First of all (you already know), add reloadOnSearch: false to your $routeProvider:

      $routeProvider.when('/somewhere', {
          controller: 'SomeCtrl',
          reloadOnSearch: false
      })
      
    2. Change your anchor tag href or ng-href to href="#/somewhere?param=value" this will trigger $routeChangeSuccess event if the path part (/somewhere) is not the same as current location. Otherwise it will trigger $routeUpdate event.

    3. Listen event on scope:

      $scope.$on("$routeUpdate", function(event, route) {
          // some code here
      });
      
    4. If you want to change search params in code, you can use $location.search() method. $location.search API.

提交回复
热议问题