AngularJS: Change hash and route without completely reloading controller

前端 未结 10 1240
鱼传尺愫
鱼传尺愫 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 19:48

    Edit

    Better approach when using ngRoute:

    /**
     * Add skipReload() to $location service.
     *
     * See https://github.com/angular/angular.js/issues/1699
     */
    app.factory('location',
      ['$rootScope', '$route', '$location',
      function($rootScope, $route, $location) {
    
      $location.skipReload = function() {
        var lastRoute = $route.current;
    
        var deregister = $rootScope.$on('$locationChangeSuccess',
                                        function(e, absUrl, oldUrl) {
          console.log('location.skipReload', 'absUrl:', absUrl, 'oldUrl:', oldUrl);
          $route.current = lastRoute;
          deregister();
        });
    
        return $location;
      };
    
      return $location;
    }]);
    

    How to use:

    app.controller('MyCtrl', ['$scope', 'location', function($scope, location) {
      $scope.submit = function() {
        location.skipReload().path(path);
      };
    }]);
    

    Old answer

    I have written a reusable factory for that based on Jens X Augustsson answer:

    app.factory('DoNotReloadCurrentTemplate', ['$route', function($route) {
      return function(scope) {
        var lastRoute = $route.current;
        scope.$on('$locationChangeSuccess', function() {
          if (lastRoute.$$route.templateUrl === $route.current.$$route.templateUrl) {
            console.log('DoNotReloadCurrentTemplate',
                        $route.current.$$route.templateUrl);
            $route.current = lastRoute;
          }
        });
      };
    }]);
    

    Works with AngularJS 1.0.6

    How to use:

    app.controller('MyCtrl',
      ['$scope', 'DoNotReloadCurrentTemplate',
      function($scope, DoNotReloadCurrentTemplate) {
    
      DoNotReloadCurrentTemplate($scope);
    }]);
    

    AngularJS issue here: https://github.com/angular/angular.js/issues/1699

提交回复
热议问题