$ location.path将哈希值更改为%23&.hash无法正常工作

Sal*_*lil 7 url url-routing angularjs angular-ui-router

我想重定向到另一个页面并且焦点应该放在一些DIVid上,让我们说'some-div-id'.我试过跟随

$location.path('/' + $scope.config_path.school + '/' +
        $routeParams.someUrl + '/#some-div-id')
Run Code Online (Sandbox Code Playgroud)

这工作正常,但它首先将#更改为%23赞

/%23some-div-id  #If '#' is not already present in the URL
/%23some-div-id#some-div-id #If '#' is laready present in the URL
/#some-div-id
Run Code Online (Sandbox Code Playgroud)

我也试过跟随

$location.path('/' + $scope.config_path.school + '/' +
        $routeParams.someUrl + '/').hash('some-div-id')
Run Code Online (Sandbox Code Playgroud)

它正在创建一个正确的URL,但不会向下滚动到DIV带有idsome-div-id

EDITED

app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    setTimeout(function() {
      if ($location.hash()) {
        $anchorScroll($location.hash());
      }
    });
  });
})

app.controller('MainCntrl', function($scope, $location, $anchorScroll, $routeParams) {
});
Run Code Online (Sandbox Code Playgroud)

此外,我试图$location.path$location.url

Pra*_*rma 6

尝试使用$location.url而不是$location.path.

根据文档,$location.path仅更改路径,而 $location.url更改路径,搜索和散列.

所以代码就像

$scope.goto = function() {
    $location.url('pageone#one');
};
Run Code Online (Sandbox Code Playgroud)

pageone状态的URL 在哪里,#one是ID

另外,为了在直接访问带有ID的URL时使用它,请使用$anchorScroll.在$stateChangeSuccess活动中,检查天气$location.hash是否存在.如果有,请拨打电话$anchorScroll.代码看起来像

.run(function($rootScope, $location, $anchorScroll,$timeout) {
    $rootScope.$on('$stateChangeSuccess',
        function(event, toState, toParams, fromState, fromParams) {
            $timeout(function() {
                if ($location.hash()) {
                $anchorScroll();
               }
          });
    });
})
Run Code Online (Sandbox Code Playgroud)

示例 - http://plnkr.co/edit/4kJjiMJImNzwLjRriiVR?p=preview(用于查看URL中的更改检查http://run.plnkr.co/plunks/4kJjiMJImNzwLjRriiVR/#/pageone)